Strings in python
• In python , a consecutive sequence of characters
enclosed in single(‘ ’)or double(“ “) quotes , is known
as a string.Triple quotes are used for strings that span
multiple lines.
Eg
F=“mango”
St=‘hello’
P=“this is anu\’s pen”
We can insert double quotes and single quotes in a string
by using backslash(\). It is called escape character.
String traversal using for loop
Eg-1 Eg-2
str="hello world"
str="hello world" l=len(str)
for c in str: for c in range(l):
print(c) print(str[c])
String traversing by while loop
str="hello world"
l=len(str)
c=0
while c<l:
print(str[c])
c=c+1
1, WAP to find the number of ‘a’ present in a
string entered at run time.
2. WAP to find the number of vowels present in
a string entered at run time.
3. WAP to add a # symbol in between each
character of a string entered at runtime.
4. WAP to count the number of occurrence of a
character in an inputted string.
Strings are immutable
The content of a string cannot be changed after
it is created.
Eg--
str=‘save money’
str*4+=‘p’ #error
Concatenation/join(+) operator
Member ship operator(in and not in)
Replication(*) operator
• It creates a new string by repeating multiple
copies of the same string.
• Eg-
st=‘hello’
print(3*st) - ‘hello hello hello’
Comparison operators
We can use relational or comparison
(<,>,<=,>=,==,!=) to compare to strings.
Eg-
s1=“mary”
s2=‘mac’
s1<s2 false
‘arrow’ >’aron’ ---True
“teeth”<“tee” ----False
Write the output of the following pgm.
a='save water'
print(a[2:5])
print(a[-5:])
print(a[:])
print(a[:6])
print(a[5:])
print(a[-6:-2])
ve
water
save water
save w
water
wat