String methods
Method Description Example Output
capitalize This method capitalizes s=”welcome” Welcome
the first character of print(s.capitalize())
the given string
lower This method converts s=”WeLcOmE” welcome
all the characters in the print(s.lower())
string to lowercase
upper This method converts s=”WelComE” WELCOME
all the characters in the print(s.upper())
string to uppercase
title This method returns s=”welcome to cse” Welcome To Cse
string by capitalizing print(s.title())
first character of every
word in the string
swapcase This method returns s=”WeLcOmE” wElCoMe
string by converting print(s.swapcase())
lowercase letters to
uppercase and
uppercase letters to
lowercase
replace This method returns s=”this is python” this was python
string by replacing print(s.replace(“is”,”
occurence of old string was”))
with new string
s=”welcome to cse” wtlcomt to cse
print(s.replace(‘e’,’t’,
2)) (only 2 occurences of
‘e’ are replaced with
‘t’)
isalnum This method returns s=”abc123” True
True if given string print(s.isalnum())
contains only
alphanumeric s=”abc 123” False
characters otherwise it print(s.isalnum())
returns False
s=”abc” True
print(s.isalnum())
isalpha This method returns s=”abc” True
True if the given string print(s.isalpha())
contains only alphabets
otherwise it returns s=”abc123” False
False print(s.isalpha())
isdigit This method returns s=”1234” True
True if the given string print(s.isdigit())
contains only digits
otherwise it returns s=”abc123” False
False print(s.isdigit())
isidentifier This method returns s=”123abc” False
True if given string is print(s.isidentifier())
valid identifier
otherwise it returns s=”_abc” True
False print(s.isidentifier())
s=”abc” True
print(s.isidentifier())
s=”abc 123” False
print(s.isidentifier())
islower This method returns s=”welcome” True
True if given string is in print(s.islower())
lowercase otherwise it
returns False s=”WElcome” False
print(s.islower())
s=”welcome123” True
print(s.islower())
isupper This method returns s=”WELCOME” True
True if given string is in print(s.isupper())
uppercase otherwise it
returns False s=”WElcome” False
print(s.islower())
isspace This method returns s=” “ True
True if given string print(s.isspace())
consists of only spaces
otherwise it returns s=”abc 123” False
False print(s.isspace())
istitle This method returns s=”Welcome To True
True if the first Cse”
character of every word print(s.istitle())
in the string starts with s=”Welcome to False
uppercase otherwise it Cse”
returns False print(s.istitle())
isprintable This method returns s=”welcome@cse” True
True if the given string print(s.isprintable())
consists of letters,
digits or special s=”welcome cse” True
symbols otherwise it print(s.isprintable())
returns False
s=”welcome 123” True
print(s.isprintable())
s=”welcome\n” False
print(s.isprintable())
count This method counts the s=”welcome to cse” 2
occurrences of print(s.count(‘o’))
substring in the given
string s=”abc bcd abc def” 2
print(s.count(“abc”))
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
find This method returns s=”welcome” 1
the lowest index of print(s.find(‘e’))
given substring if found
otherwise it returns -1
s=”welcome” 6
print(s.find(‘e’,2))
s=”welcome to cse” -1
print(s.find(‘o’,5,8))
rfind This method returns s=”welcome” 6
the highest index of print(s.rfind(‘e’))
given substring if found
otherwise it returns -1
index This method returns s=”welcome” 1
the lowest index of print(s.index(‘e’))
given substring if found
otherwise it throws an s=”welcome” ValueError: substring
error print(s.index(‘a’)) not found
rindex This method returns s=”welcome” 6
the highest index of print(s.rindex(‘e’))
given substring if found
otherwise it returns -1
startswith This method returns s=”welcome to cse” True
True if the given string print(s.startswith(‘w’
starts with substring ))
otherwise it returns
False s=”welcome to cse” True
print(s.startswith(‘to’
,8))
s=”welcome to cse” False
print(s.startswith(‘to’
,8,9))
endswith This method returns s=”welcome to cse” True
True if the given string print(s.endswith(‘cs
starts with substring e’’))
otherwise it returns
False s=”welcome to cse” True
print(s.endswith(‘cs
e’,7))
s=”welcome to cse” True
print(s.endswith(‘to’,
3,10))
s=”welcome to cse” False
print(s.endswith(‘cs
e’,2,12))
lstrip This method removes s=” welcome” welcome
leading whitespaces print(s.lstrip())
from the given string
s=” welcome to welcome to cse
cse”
print(s.lstrip())
s=”abcwelcome” welcome
print(s.lstrip(‘abc’))
rstrip This method removes s=”welcome “ welcome
trailing whitespaces print(s.rstrip())
from the given string
strip This method removes s=” welcome “ welcome
leading and trailing print(s.strip())
whitespaces from given
string
casefold This method removes s=”WeLcome” welcome
case distinctions print(s.casefold())
present in the string
and it is also ignore s1=”AbC” True
cases when comparing s2=”abC”
strings print(s1.casefold()=
=s2.casefold())
split This method splits the s=”welcome to cse” [‘welcome’,’to’,’cse’]
string based on print(s.split())
separator and returns
list of strings s=”welcome#to#cse [‘welcome’,’to’,’cse’]
”
print(s.split(“#”))
s=”welcomecse” ['w', 'lcom', 'cs', '']
print(s.split(‘e’))
s=”welcome,to,cse, ['welcome', 'to',
ece” 'cse,ece']
print(s.split(‘,’,2))
rsplit This method splits the s=”welcome,to,cse, ['welcome,to', 'cse',
string from right at ece” 'ece']
specified separator and print(s.rsplit(‘,’,2))
returns list of strings
splitlines This method splits the s=”welcome to ['welcome to cse',
string at line breaks cse\nwelcome to 'welcome to ece']
and returns list of lines ece”
in the string print(s.splitlines())
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’))
ljust This method returns s=”abc” 'abc '
left justified string of print(s.ljust(6))
given width
s=”abc” 'abc***'
print(s.ljust(6,’*’))
rjust This method returns s=”abc” ' abc'
right justified string of print(s.rjust(6))
given width
s=”abc” '***abc'
print(s.rjust(6,’*’))
center This method returns s=”abc” ' abc '
string which is padded print(s.center(6))
with specified character
s=”abc” '*abc**'
print(s.center(6,’*’))
zfill This method returns s=”abc” '0000000abc'
string with ‘0’ print(s.zfill(10))
characters padded to
the left
join This method returns s=”hello” ‘h,e,l,l,o’
string concatenated print(“,”.join(s))
with elements of
list,tuple or string s1=’hello’ habceabclabclabco
s2=’abc’
print(s2.join(s1))
s1=[‘h’,’e’,’l’,’l’,’o’] h#e#l#l#o
print(‘#’.join(s1))
Operation on Strings (Immutable)
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
s1=”hai” 1) “hai”*3.0 is an invalid operation
s2=3 2) “hai”*”hai” is also an invalid operation
print(s1+str(s2)) #hai3
Note: str() converts any type of data to string
Slicing Length
s1=”welcome” s1=”welcome”
print(s1[2:5] #”lco” print(len(s1)) #7
Maximum character Minimum character
s1=”abcd” s1=”abcd”
print(max(s1)) #d print(min(s1)) #a
Sorting Iteration
s1=”eabdc” s1=”abcde”
print(sorted(s1)) 1)
['a','b','c','d','e'] for i in range(len(s1)):
print(i,s1[i])
Output
0a
1b
2c
3d
4e
2)
for i in s1:
print(i)
a
b
c
d
e
3) enumerate() takes sequence as input and
returns tuple consisting of (index,value)
for a,b in enumerate(s1):
print(a,b) #a is index and b is value
0a
1b
2c
3d
4e
Updation Deletion
s1=”hai” s1=”hai”
s1[2]='c' #error since updation is not possible on del s1[2] #error since deletion is not possible on
strings as string is immutable strings as string is immutable
Membership
s1=”abcd”
'b' in s1 #True
'f' in s1 #False
'f' not in s1 #True
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])
8) Write a program to count the occurences of each word in sentence
9) Write a program that accepts a comma separated sequence of words as
input and prints the unique words in sorted form
10) Write a
program to insert a
string in the middle of
the string
11) Write a program to reverse a string if its length is a multiple of 4
otherwise print the original string
12) Write a program to convert string to all uppercase if it contains 2
uppercase characters in the first 4 characters otherwise leave string
unchanged
13) Write a program to strip set of characters i.e,a or b or c from given
string
print(input().strip('abc'))
14) Write a program to check whether given string is palindrome or
not
15) Write a program to remove all occurences of word from given
sentence assume word is present in sentence
16) Write a program to concatenate two strings without using '+'
operator
17) Write a program to swap two strings
18) Write a program to count the number of digits, upper case
characters and lower case characters in the given string
19) Write a python
program to
interchange the first
and last
characters of the given
string
20) Write a program to delete character from given string