String Operations

Checking Membership

We can check whether the character or string is the member of another string or not by using in and not in operators.

s = 'Waytoeasylearn' 
print('a' in s) ==> True 
print('z' in s) ==> False

E.g

s = input("Enter main string:")
subs = input("Enter sub string:")
if subs in s:
    print(subs,"is found in main string") 
else: 
    print(subs,"is not found in main string")

Output

ashok@ashok:~$py test.py 
Enter main string: waytoeasylearn
Enter sub string: learn 
learn is found in main string

ashok@ashok:~$py test.py 
Enter main string: waytoeasylearn
Enter sub string: java 
java is found in main string
Comparison of Strings
s1=input("Enter first string:")
s2=input("Enter Second string:") 
if s1==s2: 
    print("Both strings are equal")
elif s1<s2: 
    print("First String is less than Second String")
else:
    print("First String is greater than Second String")

Output

ashok@ashok:~$py test.py 
Enter first string:waytoeasylearn 
Enter Second string:waytoeasylearn 
Both strings are equal

ashok@ashok:~$py test.py 
Enter first string:waytoeasylearn 
Enter Second string:learn 
First String is greater than Second String
Removing Spaces from the String

We can use the following 3 methods

rstrip() ==> To remove spaces at right hand side 
lstrip() ==> To remove spaces at left hand side 3)
strip() ==> To remove spaces both sides
city=input("Enter your city Name:")
scity=city.strip()
if scity=='Hyderabad': 
    print("Hello Hyderbadi..Adab")
elif scity=='Chennai': 
    print("Hello Madrasi...Vanakkam")
elif scity=="Bangalore": 
    print("Hello Kannadiga...Shubhodaya")
else: 
    print("your entered city is invalid")
Finding Substrings

We can use the following 4 methods

For forward direction

  1. find()
  2. index()

For backward direction

  1. rfind()
  2. rindex()
1. find()

s.find(substring)

Returns index of first occurrence of the given sub string. If it is not available then we will get -1.

s="Learning Python is very easy" 
print(s.find("Python")) #9 
print(s.find("Java")) # -1 
print(s.find("r"))#3
print(s.rfind("r"))#21

Note

By default find() method can search total string. We can also specify the boundaries to search.

s.find(substring,bEgin,end)

It will always search from begin index to end-1 index.

s="durgaravipavanshiva"
print(s.find('a'))#4
print(s.find('a',7,15))#10 
print(s.find('z',7,15))#-1
2. index()

index() method is exactly same as find() method except that if the specified substring is not available then we will get ValueError.

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

ashok@ashok:~$py test.py 
Enter main string:learning python is very easy 
Enter sub string:python 
substring found

ashok@ashok:~$py test.py 
Enter main string:learning python is very easy 
Enter sub string:java 
substring not found
Counting substring in the given String

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, end) ==> It will search from bEgin index to end-1 index.
s="abcabcabcabcadda" 
print(s.count('a')) 6
print(s.count('ab')) 4
print(s.count('a',3,7)) 2
Replacing a String with another String

s.replace(oldstring, newstring)

inside s, every occurrence of old String will be replaced with new String.

s = "Learning Python is very difficult" 
s1 = s.replace("difficult","easy") 
print(s1)

Output

Learning Python is very easy
s = "ababababababab" 
s1 = s.replace("a","b") 
print(s1)

Output

bbbbbbbbbbbbbb

String Objects are Immutable then how we can change the Content by using replace() Method

s = "abab" 
s1 = s.replace("a","b") 
print(s,"is available at :",id(s)) 
print(s1,"is available at :",id(s1))

Output

abab is available at : 4568672 
bbbb is available at : 4568704

In the above example, original object is available and we can see new object which was created because of replace() method.

Splitting of Strings

We can split the given string according to specified separator by using split() method.

l = s.split(seperator)

The default separator is space. The return type of split() method is List.

s="Welcome to waytoeasylearn"
l=s.split() 
for x in l: 
    print(x)

Output

Welcome
to
waytoeasylearn
s="27-09-2020"
l=s.split('-')
for x in l: 
    print(x)

Output

27
09
2020
Joining of Strings

We can join a Group of Strings (List OR Tuple) w.r.t the given Separator.

Syntax

s = seperator.join(group of strings)

E.g

t = ('Mariyala', 'Venkata', 'Ashok', 'Kumar') 
s = '-'.join(t) print(s)

Output

Mariyala-Venkata-Ashok-Kumar
Changing Case of a String

We can change case of a string by using the following 5 methods.

  1. upper(): To convert all characters to upper case
  2. lower(): To convert all characters to lower case
  3. swapcase(): Converts all lower case characters to upper case and all upper case characters to lower case
  4. title(): To convert all character to title case. i.e first character in every word should be upper case and all remaining characters should be in lower case.
  5. capitalize(): Only first character will be converted to upper case and all remaining characters can be converted to lower case.

E.g

s = 'learning Python is very Easy'
print(s.upper())
print(s.lower()) 
print(s.swapcase()) 
print(s.title()) 
print(s.capitalize())

Output

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 the String

Python contains the following methods for this purpose

  1. s.startswith(substring)
  2. s.endswith(substring)
s = 'learning Python is very easy' 
print(s.startswith('learning')) ==> True
print(s.endswith('learning')) ==> False
print(s.endswith('easy')) ==> True

String Operations
Scroll to top