PYTHON STRINGS –Sample programs:
1.# create string type variables
name = "Python"
print(name)
message = "I love Python."
print(message)
Access String Characters in Python
greet = 'hello'
print(greet[1]) # "e"
# access 1st index element
2.Negative Indexing: Similar to a list, Python allows negative
indexing for its strings.
For example,
greet = 'hello'
# access 4th last element
print(greet[-4]) # "e"
3.Slicing:
Access a range of characters in a string by using the slicing
operator colon :. For example,
greet = 'Hello'
print(greet[1:4]) # "ell"
# access character from 1st index to 3rd index
4.Python Strings are immutable
message = 'Hola Amigos'
message[0] = 'H'
print(message)
Output
TypeError: 'str' object does not support item assignment
However, we can assign the variable name to a new string. For
example,
message = 'Hola Amigos'
# assign new string to message variable
message = 'Hello Friends'
prints(message); # prints "Hello Friends"
5.Python Multiline String
We can also create a multiline string in Python. For this, we
use triple double quotes """ or triple single quotes '''. For
example,
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)
O/P:
Never gonna give you up
Never gonna let you down
6.Python String Operations
Compare Two Strings
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"
print(str1 == str2)
print(str1 == str3)
# compare str1 and str2
# compare str1 and str3
O/p
False
True
n the above example,
str1 and str2 are not equal. Hence, the result is False.
str1 and str3 are equal. Hence, the result is True.
7.Join Two or More Strings
greet = "Hello, "
name = "Jack"
# using + operator
result = greet + name
print(result)
# Output: Hello, Jack
8.Iterate Through a Python String
greet = 'Hello'
# iterating through greet string
for letter in greet:
print(letter)
o/p
H
e
l
l
o
9.Python String Length
In Python, we use the len() method to find the length of a
string. For example,
greet = 'Hello'
print(len(greet))
# count length of greet string
# Output: 5
10.Python String Formatting (f-Strings)
Python f-Strings make it really easy to print values and
variables. For example,
name = 'Cathy'
country = 'UK'
print(f'{name} is from {country}')