To create a string variable, enclose characters with " " or ' '
Example:
string1 = "This is Python string 1"
string2 = 'This is Python string 2'
print(string1)
print(string2)
#output:
This is Python string 1
This is Python string 2
This is when defining strings on a single line. There exists a possibility to define a string that spread on multiple lines using triple double quotes or triple single quotes i.e. """ or '''.
Example:
string_m = """Today is Monday and
the sky is perfect clear"""
To understand the way to access elements in a string we start from analogy that Python strings are like a list of characters, hence elements can be accessed using index, negative index or even slicing notation. Exist also __getitem__() method which is a little bit similar with accessing using index.
Example using index:
mystr = "Today is Monday"
print(mystr[0])
print(mystr[1])
#output:
T
o
Example using negative index:
mystr = "Today is Monday"
print(mystr[-1])
print(mystr[-3])
#output:
Y
d
We observe that negativ index "count back" from the end of the string elements.
Example using slicing notation:
mystr = "Today is Monday"
print(mystr[0:2])
print(mystr[1:5])
#output:
To
oday
We observe that in slicing it count till "right slice value -1" means mystr[0:2] will show mystr[0], mystr[1] but will not show mystr[2]
Example using __getitem__()
mystr = "Today is Monday"
print(mystr.__getitem__(0))
#output
T
String comparison
It is performed with == operator
example:
s1="alfa"
s2="Alfa"
s3="alfa"
if(s1==s2):
print("s1 is equal with s2")
else:
print("s1 is not equal with s2")
#
if(s1==s3):
print("s1 is equal with s3")
else:
print("s1 is not equal with s3")
#output:
s1 is not equal with s2
s1 is equal with s3
We observe that == with strings is case sensitive.
The other way to compare strings is using __eq__() or __ne__()
Example:
s1="alfa"
s2="Alfa"
s3="alfa"
print(s1.__eq__(s2))
print(s1.__eq__(s3))
print(s1.__ne__(s2))
#output:
False
True
True
Thus method __eq__() return True if strings are equal, while __ne__() return True if strings are not equal. Basically == operator automatically call __eq__() method.
Concatenating or joining strings
Strings can be concatenated using "+" operator
Example:
s1 = "Alfa"
s2 = "Beta"
print(s1+s2)
#output:
AlfaBeta