Python Strings
Python Strings
s=”abc” True
print(s.isidentifier())
s=”welcome123” True
print(s.islower())
s=”welcome\n” False
print(s.isprintable())
s=”abcdbcd” 0
print(s.count(“ef”))
s=”welcome to cse” 1
print(s.count(‘o’,7))
#starts searching
for ‘o’ from 7th
position
s=”welcome to cse” 0
print(s.count(‘e’,7,1
0))
#starts searching
for ‘o’ from 7th
position and
continue till
endposition-1=10-
1=9
s=”welcome to cse” -1
print(s.find(‘o’,5,8))
s=”abcwelcome” welcome
print(s.lstrip(‘abc’))
rstrip This method removes s=”welcome “ welcome
trailing whitespaces print(s.rstrip())
from the given string
partition This method splits the s=”hi welcome to ('hi welcome ', 'to', '
string at the first everybody in the everybody in the
occurence of substring world” world')
and returns a tuple print(s.partition(‘to’))
consisting of 3 parts
1) Part before the
substring s=”hi welcome to ('hi welcome to
2) Substring everybody in the everybody in the
3) Part after the world” world', '', '')
substring print(s.partition(‘hell
o’))
s1=[‘h’,’e’,’l’,’l’,’o’] h#e#l#l#o
print(‘#’.join(s1))
Concatenation(+) Repetition(*)
s1=”hai” s1=”hai”
s2=”welcome” print(s1*3) #prints “hai” 3 times i.e.,haihaihai
print(s1+s2) #haiwelcome
Note: + is valid among the strings Note: * is possible among string and integer
Programs on Strings
1) Write a python program to get a string made of first 2 and last 2 characters from given
string. If length of string is less than 2 print “string is invalid”
n=input()
if len(n)<2:
print("string is invalid")
else:
newstring=n[:2]+n[len(n)-2:]
print(newstring)
2) Write a python program to get a string from a given string where all occurences of its
first character have been changed to $ except the first character itself
3) Write a python program to get string from two given strings separated by a space and swap the
first two characters of each string
4) Write a python program to add 'ing' at the end of the given string if length of
string is >=3 and if the given string already ends with 'ing' then add 'ly' instead. If
string length is less than 3 leave it unchanged
5) Write a function that takes list of words and returns the length of the longest one
6) Write a
program to
remove nth
index character
from non empty
string
7) Write a program to remove characters which have odd index values of given
string
s=input()
print(s[1::2])
10) Write a
program to insert a
string in the middle of
the string
print(input().strip('abc'))