Class 8(Strings)
Class 8(Strings)
A string is a:
� Sequence of characters
� Sequence of “pure” unicode characters (there is no specific encoding like UTF-8)
[2]: print(str1)
print(str2)
print(str3)
print(str4)
Hello world
new year
welcome
hi to all
Concatenation
Strings can be glued together (concatenated) with the + operator.
[4]: str5="Hello"
str6="World"
print(str5+str6)
HelloWorld
Repetition
Strings can be repeated or repeatedly concatenated with the asterisk operator ”*”.
1
[12]: print(str5*3)
HelloHelloHello
[13]: print("Repitition"*4)
RepititionRepititionRepititionRepitition
Indexing
A string can be indexed using index() method.
[15]: print(str7.index("c"))
[16]: print(str7.index("S"))
print(str7.index("n"))
print(str7.index("O"))
11
15
18
A string in Python:
� Consists of a series of characters such as letters, numbers, and special characters
� Can be subscripted or indexed (Similar to C, the first character of a string in Python has the
index 0.)
Subscripted Variable
[24]: print(str8[0])
print(str8[len(str8)-1])
print(str8[-2])
print(str8[6])
S
e
l
i
2
[26]: print("welcome"[2:4])
print("hello to all"[4:8])
lc
o to
rn s
zis pets
UPPER CASE
lower case
The startswith() method returns True if a string starts with the specified prefix(string). Else, it
returns False.
[34]: str12="string starts with demo"
print(str12.startswith("string"))
print(str12.endswith("hello"))
True
False
The split() method breaks up a string at the specified separator and returns a list of strings.
[41]: str14.split(",")
Python strings cannot be changed as change in indexed position will raise an error.
[42]: str14="strings can't be modified"
print(str14)
3
[43]: str14[10]='a'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-4b9801e2c888> in <cell line: 1>()
----> 1 str14[10]='a'
[45]: str16=str15.replace("demo","operation")
print(str16)
String operations
[49]: strip_string.strip()
[50]: strip_string.lstrip()
[51]: strip_string.rstrip()