len() Function
- We can use len() function to find the number of characters present in the string.
Example
Python
s='ajay'
print(len(s))
Output
PowerShell
4
Question
Write a program to access each character of string in forward and backward direction by using while loop?
Python
s="Learning Python is very easy !!!"
n=len(s)
i=0
print("Forward direction")
while i<n:
print(s[i],end=' ')
i+=1
print()
print("Backward direction")
i=-1
while i>=-n:
print(s[i],end=' ')
i-=1
Output
PowerShell
Forward direction
L e a r n i n g P y t h o n i s v e r y e a s y ! ! !
Backward direction
! ! ! y s a e y r e v s i n o h t y P g n i n r a e L
Alternative ways
Python
s="Learning Python is very easy !!!"
print("Forward direction")
for i in s:
print(i,end=' ')
print()
print("Backward direction")
for i in s[::-1]:
print(i,end=' ')
Output
PowerShell
Forward direction
L e a r n i n g P y t h o n i s v e r y e a s y ! ! !
Backward direction
! ! ! y s a e y r e v s i n o h t y P g n i n r a e L
Removing Spaces
- We can use the following 3 methods
- rstrip() ⇒ To remove spaces at right hand side.
- lstrip() ⇒ To remove spaces at left hand side.
- strip() ⇒ To remove spaces both sides.
Example
Python
city=input("Enter your city Name:")
city=city.strip()
print("City name -", city)
if city=='Hyderabad':
print("Hello Hyderbadi..Adab")
elif city=='Chennai':
print("Hello Madrasi...Vanakkam")
elif city=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("your entered city is invalid")
Output
PowerShell
Enter your city Name: Allahabad
City name - Allahabad
your entered city is invalid
PowerShell
Enter your city Name:Chennai
City name - Chennai
Hello Madrasi...Vanakkam
Finding Substrings
- We can use the following 4 methods
- For forward direction
- find()
- index()
- For backward direction
- rfind()
- rindex()
- For forward direction
find()
Syntax
Python
main_string.find(sub_string, begin_index, end_index)
- Return index of first occurrence of the given substring between begin_index and end_index. If it is not available then we will get -1.
- default value of begin_index = 1 and end_index = length of string.
Example
Python
s="Learning Python is very easy"
print(s.find("Python"))
print(s.find("Java"))
print(s.find("r"))
print(s.rfind("r"))
Output
Python
9
-1
3
21
Example
Python
s="Learning Python is very easy"
print(s.find("Python", 7, 15))
print(s.find("Java, 7, 15"))
print(s.find("o", 7, 15))
print(s.rfind("r", 7, 15))
Output
Python
9
-1
13
-1
index()
- index() method is exactly same as find() method except that if the specified substring is not available then we will get ValueError.
Example
Python
s=input("Enter main string:")
subs=input("Enter sub string:")
try:
n=s.index(subs)
except ValueError:
print("substring not found")
else:
print("substring found")
Output
PowerShell
Enter main string:learning python is very easy
Enter sub string:python
substring found
PowerShell
Enter main string:learning python is very easy
Enter sub string:java
substring not found
Question
Display all positions of substring in a given main string
Python
s=input("Enter main string:")
subs=input("Enter sub string:")
flag=False
pos=-1
n=len(s)
while True:
pos=s.find(subs,pos+1,n)
if pos==-1:
break
print("Found at position",pos)
flag=True
if flag==False:
print("Not Found")
Output
PowerShell
Enter main string:ajay shukla
Enter sub string:a
Found at position 0
Found at position 2
Found at position 10
Counting Substring
- We can find the number of occurrences of substring present in the given string by using count() method.
- s.count(substring) ⇒ It will search through out the string.
- s.count(substring, begin_index, end_index) ⇒ It will search from begin_index to end_index-1.
Example
Python
s="abcabcabcabcadda"
print(s.count('a'))
print(s.count('ab'))
print(s.count('a',3,7))
Output
PowerShell
6
4
2
Replacing Substring
- s.replace(old_string, new_string)
- Inside s, every occurrence of old_string will be replaced with new_string.
Example
Python
s="Learning Python is very difficult"
s1=s.replace("difficult","easy")
print(s1)
Output
PowerShell
Learning Python is very easy
Example
Python
s="ababababababab"
s1=s.replace("a","b")
print(s1)
Output
PowerShell
bbbbbbbbbbbbbb
Question
String objects are immutable then how we can change the content by using replace() method.
Answer
- Once we creates string object, we cannot change the content. This non changeable behavior’s is nothing but immutability. If we are trying to change the content by using any method, then with those changes a new object will be created and changes won’t be happened in existing object.
- Hence with replace() method also a new object got created but existing object won’t be changed.
Python
s="abab"
s1=s.replace("a","b")
print(s,"is available at :",id(s))
print(s1,"is available at :",id(s1))
Output
Python
abab is available at : 2711833054000
bbbb is available at : 2711839144688
Splitting of Strings
- We can split the given string according to specified separator by using split() method.
- s.split(separator)
- The default separator is space.
- The return type of split() method is list.
Example
Python
s="internet knowledge hub"
l=s.split()
for x in l:
print(x)
Output
PowerShell
internet
knowledge
hub
Example
Python
s="22-02-2018"
l=s.split('-')
for x in l:
print(x)
Output
PowerShell
22
02
2018
Joining of Strings
- We can join a group of strings (list or tuple) wrt the given separator.
- seperator.join(group of strings)
Example
PowerShell
my_tuple=('internet','knowledge','hub')
s='-'.join(my_tuple)
print(s)
Output
PowerShell
internet-knowledge-hub
Example
PowerShell
my_list=['internet','knowledge','hub']
s=':'.join(my_list)
print(s)
Output
PowerShell
internet:knowledge:hub
Changing Case of String
- We can change case of a string by using the following 5 methods.
- upper() ⇒ To convert all characters to upper case.
- lower() ⇒ To convert all characters to lower case.
- swapcase() ⇒ converts all lower case characters to upper case and all upper case characters to lower case.
- title() ⇒To convert all character to title case. First character in every word should be upper case and all remaining characters should be in lower case.
- capitalize() ⇒ Only first character will be converted to upper case and all remaining characters can be converted to lower case.
Example
Python
s='learning Python is very Easy'
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())
Output
PowerShell
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
Checking Starting And Ending Part of String
- Python contains the following methods for checking start and end word in string.
- s.startswith(substring)
- s.endswith(substring)
Example
Python
s='learning Python is very easy'
print(s.startswith('learning'))
print(s.endswith('learning'))
print(s.endswith('easy'))
Output
PowerShell
True
False
True
To Check Type Of Characters in String
- Python contains the following methods for this purpose.
- isalnum() ⇒ Returns True if all characters are alphanumeric ( a to z, A to Z, 0 to9 ).
- isalpha() ⇒ Returns True if all characters are only alphabet symbols (a to z, A to Z).
- isdigit() ⇒ Returns True if all characters are digits only ( 0 to 9).
- islower() ⇒ Returns True if all characters are lower case alphabet symbols.
- isupper() ⇒ Returns True if all characters are upper case alphabet symbols.
- istitle() ⇒ Returns True if string is in title case.
- isspace() ⇒ Returns True if string contains only spaces.
Example
Python
print('Internet786'.isalnum())
print('Internet786'.isalpha())
print('Internet'.isalpha())
print('Internet'.isdigit())
print('786786'.isdigit())
print('Internet'.islower())
print('Internet'.islower())
print('abc123'.islower())
print('ABC'.isupper())
print('Learning python is Easy'.istitle())
print('Learning Python Is Easy'.istitle())
print(' '.isspace())
Output
Python
True
False
True
False
True
False
False
True
True
False
True
True
Example
Python
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lower case alphabet character")
else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
else:
print("Non Space Special Character")
Output
PowerShell
Enter any character:7
Alpha Numeric Character
it is a digit
PowerShell
Enter any character:a
Alpha Numeric Character
Alphabet character
Lower case alphabet character
PowerShell
Enter any character:$
Non Space Special Character
PowerShell
Enter any character:A
Alpha Numeric Character
Alphabet character
Upper case alphabet character
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!