Strings
Strings
gs
String is a sequence which is made up of one or more
UNICODE characters. Here the character can be a
letter, digit, whitespace or any other symbol. A string
can be created by enclosing one or more characters in
single, double or triple quote.
Example
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''
String is Immutable
A string is an immutable data type. It means that the
contents of the string cannot be changed after it has
been created. An attempt to do this would lead to an
error.
>>> str1 = "Hello World!"
#if we try to replace character 'e' with 'a' >>> str1[1] =
'a'
TypeError: 'str' object does not support item
assignment
String Operations(concatenation, repetition,
membership and slicing.)
1. Concatenation(‘+’) – To Join
>>> str1 = 'Hello' #First string
>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings
'HelloWorld!'
2. Repetition(‘*’) – To repeat a string
>>> str1 = 'Hello' #repeat the value of str1
>>> str1 * 2 'HelloHello'
3. Membership( ‘in’ and ‘not in’)
The 'in' operator takes two strings and returns
True if the first string appears as a substring in the
second string, otherwise it returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1 True
>>> 'Wor' in str1 True
>>> 'My' in str1 False
4. Slicing(str1[n:m])
In Python, to access some part of a string or
substring, we use a method called slicing. This can
be done by 2024-25 Strings 179 specifying an
index range. Given a string str1, the slice operation
str1[n:m] returns the part of the string str1
starting from index n (inclusive) and ending at m
(exclusive).
>>> str1 = 'Hello World!'
>>> str1[1:5] 'ello'
>>> str1[7:10] 'orl'
>>> str1[3:20] 'lo World!'
Traversing a String
We can access each character of a string or
traverse a string using for loop and while loop. (A)
String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch,end = '')
Hello World! #output
while Loop:
>>> str1 = 'Hello World!'
>>> index = 0
>>> while index < len(str1):
print(str1[index],end = '')
index += 1
Hello World! #output