Python String Methods Tutorial

Table of Contents


In this tutorial we will learn about Python String Methods. In python programming, String methods are many types like counts(), split(), strip(), lower(), upper(), center(), find(), index(), format(), etc.

Python string methods

Python String Methods Are Given As:


Python String count()

In the python string methods, the Count() method is used to count the substring from the given string. count() method returns the number of occurrences of the substring in the given string. It takes three parameters substring, start_index, end_index. In which start_index and end_index are optional parameters.

Syntax of Python String count() :    string.count(substring, start_index, end_index)

Example of python string count() method

python string count

Code

#string
string = 'Technoelearn is the learning site'

#count the substring 'rn'
string.count('rn')
Output : 2

Python String center()

In python string methods, The center() method is used to cetered the string and it return the string which is padded with fillchar. It takes two argument width and fillchar, where fillchar is optional. If fillchar is not included in method. So, by default it is blank space.

Syntax of Python String center() :    string.center(width, fillchar)

Example of python string center() method

python string center method

Code

#string
string = 'Technoelearn'

# centered the string and fill with *
new_string = string.center(20, '*')

#print the new_string
print(new_string)
Output : ****Technoelearn****

Python String find()

In the python string methods, the find() method is used to find the first occurrence of a substring in the given string. It takes three parameters substring, start_index, and end_index. Where start_index and end_index is the optional parameter. If the substring is not found in the given string then find() method returns -1. It returns the index of the substring.

Syntax of Python String find() :    string.find(substring, start_index, end_index)

Example of python string find() method

python string find method

Code

#string
string = 'Technoelearn is the learning site'

#find the index of substring 'rn'
string.find('rn', 2, -1 )
Output : 10

Python String rfind()

In the python string methods, The rfind() method is used to find the highest index of a substring in the given string. It takes three arguments substring, start_index, and end_index. Whereas Start_index and end_index are optional. If these optional arguments are not included that means searching substring start from starting index and end at last index of the given string. If substring not found in the given string then return as -1.

Syntax of Python String rfind() :    string.rfind(substring, start_index, end_index)

Example of python string rfind() method

python string rfind method

Code

#string
string = 'Technoelearn is the learning site'

#find the highest index of substring 'rn'
r_index = string.rfind('rn', 2, -1 )

print(r_index)
Output : 23

Python String index()

In the python string methods, The index() method is used to find the index of a substring from the given string. It takes three arguments substring, start_index, and end_index. Whereas start_index and end_index are optional arguments. If the substring is not found in the given string then it raises an exceptional error (ValueError exception). It is similar to find() method.

Syntax of Python String index() :    string.index(substring, start_index, end_index)

Example of python string index() method

python string index method

Code

#string
string = 'Technoelearn is the learning site'

#find the index of substring 'rn'
index = string.index('rn', 2, -1 )

print(index)
Output : 10

Python String rindex()

In python string methods, The rindex() method is used find the highest index of the substring in the given string. It takes 3 arguments substring, start_index, and end_index. Whereas start_index and end_index are optional arguments. If not included then, searching start from 0 index and end at -1 index. If substring is not found in the given string, then it raise an exception (ValueError Exception).

Syntax of Python String rindex() :    string.rindex(substring, start_index, end_index)

Example of python string rindex() method

python string rindex method

Code

#string
string = 'Technoelearn is the learning site'

#find the heighest index of substring 'rn'
rindex = string.rindex('rn', 2, -1 )

print(rindex)
Output : 23

Python String expandtabs()

In the python string methods, expandtabs() method is used to give the spaces where ‘ \ t ‘ is used. by default, the tab has 8 blank spaces. expandtabs take a single argument tab_size which is optional. It returns a string where all ‘ \ t ‘ are replaced by blank spaces.

Syntax of Python String expandtabs() :    string.expandtabs(tab_size)

Example of python string expandtabs() method

python string expandtabs method

Code

#string
string = 'Technoelear\tis\tthe\tlearning\tsite'

#use expandtabs to give spaces on the place of '\t'
string = string.expandtabs(5)

print(string)
Output : Technoelear     is      the      learning     site

Python String capitalize()

In the python string methods, The capitalize() method is used to capitalize the first letter and lowercase of other letter of the sentence. it doesn’t takes any arguments.

Syntax of Python String capitalize() :    string.capitalize()

Example of python string capitalize() method

python string capitalize method

Code

#string
string = 'technoelearN is The Learning Site'

#Use capitalize() function
string = string.capitalize()

print(string)
Output : Technoelearn is the learning site

Python String lower()

In the python string methods, python lower() function is used to convert all the uppercase character into lowercase character. It doesn’t take any arguments.

Syntax of Python String lower() :    string.lower()

Example of python string lower() method

python string lower method

Code

#string
string = 'TECHNOELEARN is The Learning Site'

#Use lower() function
string = string.lower()

print(string)
Output : technoelearn is the learning site

Python String upper()

In python string methods, The python upper() function is to convert all character from lowercase to uppercase character. It doesn’t take any arguments.

Syntax of Python String upper() :    string.upper()

Example of python string upper() method

python string upper method

Code

#string
string = 'Technoelearn is The Learning Site'

#Use upper() function
string = string.upper()

print(string)
Output : TECHNOELEARN IS THE LEARNING SITE

Python String casefold()

In the python string methods, the python casefold() function is used to compare the string without any case or caseless matching of strings. It ignore whatever the string case. It doesn’t take any arguments. The casefold() function returns the casefolded string.

Syntax of Python String casefold() :    string.casefold()

Example of python string casefold() method

python string casefold method

Code

#strings
string1 = 'tECHnoEleaRN'
string2 = 'TechNOeLEArn'

#print casefolded string
print(string1.casefold())

#check the string are equal or not
if string1.casefold() == string2.casefold():
  print('String are equal')
else:
  print('string are not equal')
Output : technoelearn String are equal

Python String endswith()

In the python string methods, the python endswith() function is used to check the string is ending with the given string. If the string is ending with the specified suffix, the return True otherwise returns False. It takes three parameters suffix, start_index, and end_index. Whereas start_index and end_index are optional and if not included then the string starts at index 0 to index -1.

Syntax of Python String endswith() :    string.endswith(suffix, start_index, end_index)

Example of python string endswith() method

python string endswith method

Code

#string
string = 'Technoelearn'

#Use endswith() function
result = string.endswith('learn', 1)

print(result)
Output : True

Python String encode()

In python string methods, the python encode() function is used to convert Unicode into any encoded string which supported by python language. By default python use utf-8 encoding. If any error raise then it return UnicodeDecodeError. It takes some parameter like, encoding, error.

Syntax of Python String encode() :    string.encode()

Example of python string encode() method

python string encode method

Code

#string
string = 'Tecḥneōl̥eār̥n'

#Use encode() function
result = string.encode()

print(result)
Output : b'Tec\xe1\xb8\xcc\xa5e\ xc4\x81r\xcc\xa5n'

Python String format()

In python string methods, the format() function is used to format the given string with their new positional value to get better outputs. The format() function take two types of parameters:

Positional Parameter: In this parameter, The value are accessed on the basis of index which are in the curly barcess {0}.

Keyword Parameter: In this parameter, the value are accessed on the basis of key = value.

The format() method returns the formatted string.

Syntax of Python String format() :    string.format(string)

Example of python string format() method

string format method

Code

#Positional argument
print('Hello, My name is {0}.'.format('Alina'))

#keyword argument
print('Hey, I {n}, in class {c}.'.format(n='John', c=8))
Output : Hello, My name is Alina.
                 Hey, I John, in class 8.

Python String join()

In the python string methods, The join() function is used to join all the elements of iterable and separated by the string separator. It joins each iterable elements such as list, string, and tuple. The join() method returns by concatenating the string separator.

Syntax of Python String join() :    string.join(iterable)

Example of python string join() method

python string join method

Code

#join() method is used in list
sub_list = ['Math', 'Science', 'Hindi']
sep = ', '

print(sep.join(sub_list))

#join() method is used in tuple
sub_tuple = ('Math', 'Science', 'Hindi')
sep = '--> '

print(sep.join(sub_list))
Output : Math, Science, Hindi 
                 Math--> Science--> Hindi

Python String swapcase()

In the python string methods, The swapcase() function is used to convert all uppercase into lowercase character and lowercase into uppercase character. swapcase() function is doesn’t take any parameters. It returns the string where all the uppercase character is converted into lowercase characters and lowercase characters into uppercase characters.

Syntax of Python String swapcase() :    string.swapcase()

Example of python string swapcase() method

python string swapcase method

Code

#string
string = 'TECHNOELEARN is The Learning Site'

#Use swapcase() function
string = string.swapcase()

print(string)
Output : technoelearn IS tHE lEARNING sITE

Python String partition()

In python string methods, The partition() function is used to split the first occurrence of string into two different parts and separated by the separator. partition() function takes one parameter separator. The partition() function returns the three tuples which are separated by the separator.

Syntax of Python String partition() :    string.partition(separator)

Example of python string partition() method

python string partition method

Code

#string
string = 'Technoelearn is the learning site'

#When string found, partition() function 
f_string = string.partition('is ')
print(f_string)

#When string not found, partition() function 
n_string = string.partition('my ')
print(n_string)
Output : ('Technoelearn ', 'is ', 'the learning site') 
                  ('Technoelearn is the learning site', '', '')

Python String rpartition()

In the python string methods, The rpartition is used to split the string which comes at last occurrence in the string. The rpartition() function returns the tuples which are separated by using comma (,). It takes a string parameter called a separator.

Syntax of Python String rpartition() :    string.rpartition(separator)

Example of python string rpartition() method

python string rpartition method

Code

#string
string = 'Technoelearn is the learning is site'

#When string found, rpartition() function 
f_string = string.rpartition('is ')
print(f_string)

#When string not found, rpartition() function 
n_string = string.rpartition('my ')
print(n_string)
Output : ('Technoelearn is the learning ', 'is ', 'site') 
               ('', '', 'Technoelearn is the learning is site')

Python String strip()

In the python string methods, the strip() function is used to remove the character from both sides based on the strip arguments. By default, the strip() function remove all the blank spaces from both sides. It takes a string type of argument for which the character are removed from the given string. It returns the removed character strings. It is case sensitive in nature.

Syntax of Python String strip() :    string.strip(char)

Example of python string strip() method

python string strip method

Code

#string
string = '   Technoelearn Learning Site   '

#print string without blank spaces
print(string.strip())

#print string without spaces and t char
print(string.strip('te '))
Output : Technoelearn Learning Site 
                chnoelearn Learning Sit

Python String lstrip()

In the python string methods, The lstrip() function is used to remove the left side char or spaces from the given string. If any character is not provided in the arguments, then by default it only removes the left side blank spaces. It returns the string with removed character and blank spaces from the left side.

Syntax of Python String lstrip() :    string.lstrip(char)

Example of python string lstrip() method

python string lstrip method

Code

#string
string = '   Technoelearn Learning Site   '

#print str, by using lstrip (without char)
print(string.lstrip())

#print str, by using lstrip (with char)
print(string.lstrip(' Te'))
Output : Technoelearn Learning Site          
                chnoelearn Learning Site     

Python String rstrip()

In the python string methods, The rstrip() function is used to remove the right side char or spaces from the given string. If any character is not provided in the arguments, then by default it only removes the right side blank spaces. It returns the string with removed character and blank spaces from the right side.

Syntax of Python String rstrip() :    string.rstrip(char)

Example of python string rstrip() method

python string rstrip method

Code

#string
string = '   Technoelearn Learning Site   '

#print str, by using rstrip (without char)
print(string.rstrip())

#print str, by using rstrip (with char)
print(string.rstrip(' te'))
Output :       Technoelearn Learning Site 
                       Technoelearn Learning Si

Python String maketrans()

In the python string methods, The maketrans() function is used for mapping the tables and translate the character into their ASCII value. It returns the translation table where one to one mapping and translates in the Unicode order. It takes 3 parameters a, b, & c. where b and c are optional.

Syntax of Python String maketrans() :    string.maketrans(sub_string, start_index, end_index)

Example of python string maketrans() method

python string maketrans method

Code

# take 1st example in dictionary
dict_ele = {"a": "146", "b": "328", "c": "586"}
string = "abc"
#print by using maketrans()
print(string.maketrans(dict_ele))

#take 2nd example dictionary
dict = {97: "123", 98: "456", 99: "789"}
string = "abc"
#print by using maketrans()
print(string.maketrans(dict))
Output : {97: '146', 98: '328', 99: '586'} 
                 {97: '123', 98: '456', 99: '789'}

Python String replace()

In python string Methods, the replace() method is used to replace all occurrence of character or word with new character or word for the given string. It takes three parameters new_string, old_string, Count. Where the count parameter is optional. If not provided then the replacement of all old substring with a new substring.

Syntax of Python String replace() :    string.replace(old_string, new_string, count)

Example of python string replace() method

python string replace method

Code

#given String
string = 'My name is Alina'
print('old String :', string)

#replace the string Alina
new_string = string.replace('Alina', 'John')
print('New String :', new_string)
Output : old String : My name is Alina 
                 New String : My name is John

Python String translate()

Syntax of Python String translate() :    string.translate(sub_string, start_index, end_index)

Example of python string translate() method

Code

Output : 

Python String split()

Syntax of Python String split() :    string.split(sub_string, start_index, end_index)

Example of python string split() method

Code

Output : 

Python String rsplit()

Syntax of Python String rsplit() :    string.rsplit(sub_string, start_index, end_index)

Example of python string rsplit() method

Code

Output : 

Python String splitlines()

Syntax of Python String splitlines() :    string.splitlines(sub_string, start_index, end_index)

Example of python string splitlines() method

Code

Output : 

Python String ljust()

Syntax of Python String ljust() :    string.ljust(sub_string, start_index, end_index)

Example of python string ljust() method

Code

Output : 

Python String rjust()

Syntax of Python String rjust() :    string.rjust(sub_string, start_index, end_index)

Example of python string rjust() method

Code

Output : 

Python String isalnum()

Syntax of Python String isalnum() :    string.isalnum(sub_string, start_index, end_index)

Example of python string isalnum() method

Code

Output : 

Python String isalpha()

Syntax of Python String isalpha() :    string.isalpha(sub_string, start_index, end_index)

Example of python string isalpha() method

Code

Output : 

Python String isdigit()

Syntax of Python String isdigit() :    string.isdigit(sub_string, start_index, end_index)

Example of python string isdigit() method

Code

Output : 

Python String isdecimal()

Syntax of Python String isdecimal() :    string.isdecimal(sub_string, start_index, end_index)

Example of python string isdecimal() method

Code

Output : 

Python String isidentifier()

Syntax of Python String isidentifier() :    string.isidentifier(sub_string, start_index, end_index)

Example of python string isidentifier() method

Code

Output : 

Python String isnumerical()

Syntax of Python String isnumerical() :    string.isnumerical(sub_string, start_index, end_index)

Example of python string isnumerical() method

Code

Output : 

Python String islower()

Syntax of Python String islower() :    string.islower(sub_string, start_index, end_index)

Example of python string islower() method

Code

Output : 

Python String isprintable()

Syntax of Python String isprintable() :    string.isprintable(sub_string, start_index, end_index)

Example of python string isprintable() method

Code

Output : 

Python String isspace()

Syntax of Python String isspace() :    string.isspace(sub_string, start_index, end_index)

Example of python string isspace() method

Code

Output : 

Python String istitle()

Syntax of Python String istitle() :    string.istitle(sub_string, start_index, end_index)

Example of python string istitle() method

Code

Output : 

Python String isupper()

Syntax of Python String isupper() :    string.isupper(sub_string, start_index, end_index)

Example of python string isupper() method

Code

Output : 

Video Tutorial Of Python String Methods-1

Video Tutorial Of Python String Methods-2

https://www.youtube.com/watch?v=f28jEsTEdII

Learn More Python Tutorial:

If you have any queries regarding python string methods, then ask on the comment section, I am happy to answer your question

3 thoughts on “Python String Methods Tutorial”

Leave a Comment

Share via
Copy link
Powered by Social Snap