Python String Methods

Methods are the functions defined inside a class. Python string is also one of the predefined classes. Python string methods help to modify the string appearance and also can perform many other tasks.

MethodsUses
capitalize()returns the string where the first character is in uppercase.
title()returns the string where the first character of every word is in uppercase.
upper()returns the string where every character is in uppercase.
casefold()returns the string where every character is in lowercase.
lower()same as casefold()
swapcase()exchange the uppercase and lowercase.
count()returns the count of appearance of a character in a string.
find()returns the index of the first occurrence of a searched character. Finding direction is left to right.
rfind()returns the index of the first occurrence of a searched character. Finding direction is right to left.
index()similar to find()
replace()replace characters of a string with provided characters.
expandtabs()manipulate the size of the tab used in a string.
center()align the string in the center
ljust()left-justified strings filling characters to left
rjust()right-justified strings filling characters from right
zfill()adds zeros to the beginning of the strings.
split()split the string into the list
rsplit()split the string into the list but right to left.
splitlines()split the string into the list at new line escape character
partition()split the string into the tuple containing three elements
rpartition()split the string into the tuple from right
join()joins the iterable with the provided string
strip()removes the leading and trailing given provided character
rstrip()removes the trailing character from a string
lstrip()removes the leading character from a string
isalnum()returns True if the string contains only the alphabet and numbers.
isalpha()returns True if the string contains only the alphabet.
isnumeric()returns True if the string contains only the numeric value.
isupper()returns True if the string contains only uppercase characters.
islower()returns True if the string contains only lowercase characters.
isspace()returns True if the string contains only spaces.
istitle()returns True if the first character of every word in a string is un uppercase.
startswith()returns True if the string starts with certain characters.
endswith()returns True if the string ends with certain characters.

Python Strings Capitalize() method

The syntax is: string_name.capitalize()

This method returns the string with the first character in uppercase.

# capitalize() method
str1 = "hi, how are you?"
str2 = "Hi, how are you?"
print(str1.capitalize())
print(str2.capitalize())

Output:

Hi, how are you?
Hi, how are you?

Remember: If the first character of a given string is already in uppercase, it returns the same.

Python Strings Title() method

The syntax is: string_name.title()

This method returns the string where every first character of a word is changed to uppercase.

# title() method
str1 = "I love python. Do you?"
print(str1.title())

Output:

I Love Python. Do You?

Python Strings upper() method

The syntax is: string_name.upper()

This method returns the string where every character is in uppercase.

# upper() method
str1 = "I love python. Do you?"
print(str1.upper())

Output:

I LOVE PYTHON. DO YOU?

Python Strings casefold() method

The syntax is: string_name.casefold()

This method returns the string where every character is in lowercase. It works opposite of upper().

# casefold() method
str1 = "LaTeX is powerful tool AND is still widely used."
print(str1.casefold())

Output:

latex is powerful tool and is still widely used.

Python Strings lower() method

The syntax is: string_name.lower()

This method also returns the string where every character is in lowercase. It works just like lower(). But using casefold() is highly recommended for high performance.

# lower() method
str1 = "LaTeX is powerful tool AND is still widely used."
print(str1.lower())

Output:

latex is powerful tool and is still widely used.

Python Strings swapcase() method

The syntax is: string_name.swapcase()

This method returns the string where uppercase and lowercase are exchanged.

# swapcase() method
str1 = "LaTeX Is Powerful Tool AND is Still Widely USED."
print(str1.swapcase())

Output:

lAtEx iS pOWERFUL tOOL and IS sTILL wIDELY used.

Python Strings count() method

The syntax is: string_name.count(value, [start_index], [end_index])

This method returns the number of times that value appeared in the string. The value may be a single character or group of characters. The start_index and end_index are optional and if provided, the counting begins from the start_index and stops before end_index. Default counting is done throughout the string.

Counting single character:

# count() method
str1 = "LaTeX is powerful tool AND is still widely used."
print(str1.count('i'))         # counting throughout the string
print(str1.count('i', 7))      # counting begin from index 7
print(str1.count('i', 7, 37))  # begin: index 7 end: index 36

Output:

4
3
2

Counting characters:

# count() method
str1 = "LaTeX is powerful tool AND is still widely used."
print(str1.count('still'))       
print(str1.count('ful'))      
print(str1.count(' '))        # counting space 

Output:

1
1
8

Python Strings find() method

The syntax is: string_name.find(value, [start_index], [end_index])

This method searches the value in the string and returns the index of the first occurrence of that value. It returns -1 if the value is not found.

# find() method
str1 = "I love Python"
print(str1.find('o'))       
print(str1.find('o', 5))     # searches 'o' after index 5
print(str1.find('a'))        # returns -1 if not found

Output:

3
11
-1

Python Strings rfind() method

The syntax is: string_name.rfind(value, [start_index], [end_index])

This method searches the value in the string in reverse order (i.e. right to left) and returns the index of the first occurrence of that value. It returns -1 if the value is not found.

# rfind() method
str1 = "I love Python"
print(str1.rfind('o'))       
print(str1.rfind('o', 12))     
print(str1.rfind('a'))        # returns -1 if not found

Output:

11
-1
-1

Python Strings index() method

The syntax is: string_name.index(value, [start_index], [end_index])

This method also searches the value in the string and returns the index of the first occurrence of that value. It works just like find() method but the only difference is it raises an error if the value is not found in the string.

# index() method
str1 = "I love Python"
print(str1.index('o'))       
print(str1.index('o', 5))     # searches 'o' after index 5
print(str1.index('a'))        

Output:

3
11
Traceback (most recent call last):
  File "/home/......../python_string_method.py", line 5, in <module>
    print(str1.index('a'))        
ValueError: substring not found

Python Strings replace() method

The syntax is: string_name.replace(old_value, new_value, [count])

This method is used to replace certain characters with other characters. It replaces the old_value with new_value and returns a new string. The number of replacements happens equally to the count value. The default value of the count is a number of possible replacements.

# python strings replace() method
str_eg = 'I love Python'
print(str_eg.replace('o', 'O'))       # all replacements
print(str_eg.replace('o', 'O', 1))    # only one time replacement
print(str_eg.replace('lo', 'ol'))     # replacement of two characters

Output:

I lOve PythOn
I lOve Python
I olve Python

Python Strings expandtabs() method

The syntax is: string_name.expandtabs(tabsize)

There should be tab escape characters in a string for this method to work. This method can manipulate the tab size (i.e number of spaces).

# python strings expandtabs() method
str_eg = "Pyth\ton"
print(str_eg)
print(str_eg.expandtabs(10))

Output:

Pyth    on
Pyth      on

Python Strings center() method

The syntax is: string_name.center(length, [character])

This method aligns the strings in the middle of the provided length filled with the provided character. If the character is not given, spaces will fill the remaining length.

# python strings center() method
str_eg = "python"
print(str_eg)
print(str_eg.center(25, '-'))
print(str_eg.center(30, '#'))
print(str_eg.center(30))

Output:

python
----------python---------
############python############
            python      

Remember: The fill character cannot be more than one character.

# python strings center() method
str_eg = "python"
print(str_eg.center(25, '-'))
print(str_eg.center(25, '--'))
----------python---------
Traceback (most recent call last):
  File "/home/........../python_string.py", line 4, in <module>
    print(str_eg.center(25, '--'))
TypeError: The fill character must be exactly one character long

Python Strings ljust() method

The syntax is: string_name.ljust(value, character)

This method aligns the strings to the left side filling the value width with provided character. The value should be greater than the length of the string for the effects to be seen. The Default character is space.

# python strings ljust() method
str_eg = "python"
print(str_eg.ljust(8, '-'))
print(str_eg.ljust(10, '#'))
print(str_eg.ljust(10))

Output:

python--
python####
python 

Remember: The fill character should be exactly one character long.

Python Strings rjust() method

The syntax is: string_name.rjust(value, character)

This method aligns the strings to the left side filling the value width with provided character. The value should be greater than the length of the string for the effects to be seen. The Default character is space.

# python strings rjust() method
str_eg = "python"
print(str_eg.rjust(8, '-'))
print(str_eg.rjust(10, '#'))
print(str_eg.rjust(10))

Output:

--python
####python
    python

Remember: The fill character should be exactly one character long.

Python Strings zfill() method

The syntax is: string_name.zfill(length)

This method adds zeros to the beginning to match the length of the string to the provided length.

# python strings rjust() method
str_eg = "python"
print(str_eg.zfill(15))
print(str_eg.zfill(10))

Output:

000000000python
0000python

Remember: The value of length should be greater than the length of string itself.

Python Strings split() method

The syntax is: string_name.split(separator)

This method splits the string into a list with a specified separator. The default value of the separator is space.

So split() method breaks down a string at every space(default value of separator) and puts all the parts in a list.

# python strings split() method
str_eg = "I love Python becuause it is dynamic"
print(str_eg)
print(str_eg.split())

Output:

I love Python becuause it is dynamic
['I', 'love', 'Python', 'becuause', 'it', 'is', 'dynamic']

Now let’s give separator value and see the change.

# python strings split() method
str_eg = "I love Python becuause it is dynamic"
print(str_eg)
print(str_eg.split('o'))     # breaking point is 'o'
I love Python becuause it is dynamic
['I l', 've Pyth', 'n becuause it is dynamic']

Python Strings rsplit() method

The syntax is: string_name.rsplit(separator, [maxsplit])

This method splits the string into a list with a specified separator. The default value of the separator is space.

The rsplit() method breaks down a string from the right side at every space(default value of separator) and puts all the parts in a list. The use of maxsplit parameter controls the number of splitting breaking points.

# python strings split() method
str_eg = "I love Python becuause it is dynamic"
print(str_eg)
print(str_eg.rsplit('o',1))        # max breaking point is 1 
                                   # breaking starts from right to left     

Output:

I love Python becuause it is dynamic
['I love Pyth', 'n becuause it is dynamic']

Python Strings splitlines() method

The syntax is: string_name.splitlines()

This method also splits the string into a list. The breaking occurs at new lines escape character.

# python strings splitlines() method
str_eg = "First line\nsecond line\nthird line"
print(str_eg)
print(str_eg.splitlines())

Output:

First line 
second line 
third line
['First line', 'second line', 'third line']

Python Strings partition() method

The syntax is: string_name.partition(value)

This method breaks the strings at the first occurrence of a given value and returns a tuple containing three elements: characters before value, value, and characters after value.

# python strings partition() method
str_eg = "I love python"
print(str_eg.partition('love'))
print(str_eg.partition('p'))

Output:

('I ', 'love', ' python')
('I love ', 'p', 'ython')

If provided value is not found in strings, this method creates a tuple containing three elements, where the first element is whole strings and the remaining two are empty strings.

str_eg = "I love python"
print(str_eg.partition('a'))
('I love python', '', '')

Python Strings rpartition() method

The syntax is: string_name.rpartition(value)

This method also breaks the strings at the first occurrence of a given value and returns a tuple containing three elements but it starts to search the value in the strings from the right side.

# python strings partition() and rpartition() method
str_eg = "XYZYZX"
print(str_eg.partition('Z'))
print(str_eg.rpartition('Z'))

Output:

('XY', 'Z', 'YZX')
('XYZY', 'Z', 'X')

Python Strings join() method

The syntax is: strings.join(iterable)

This method takes all the items of iterable like list, tuple and joins them in a string. The new string formed will have all items of iterable and provided strings between each item.

# python strings join() method
l1 = ['a', 'b', 'c']       # - as strings to join list items
print('-'.join(l1))
t1 = ('a', 'b', 'c')
print('# #'.join(t1))      #  The # # as strings to join tuple items
str1 = "bikash"
print(' '.join(str1))      # space as strings to join string items

Output:

a-b-c
a# #b# #c
b i k a s h

Python Strings strip() method

The syntax is: strings.strip(character)

This method removes the leading and trailing character from strings. The default character is space.

# python strings strip() method
str1 = "-----PYTHON----"
print(str1.strip('-'))
str2 = "I love Python"
print(str2.strip('I'))
str3 = "    Python    "
print(str3.strip())
str4 = "AaBBCCAa"
print(str4.strip('Aa'))

Output:

PYTHON
 love Python
Python
BBCC

Python Strings rstrip() method

The syntax is: strings.rstrip(character)

This method removes only the trailing character from strings. The default character is space.

# python strings rstrip() method
str1 = "-----PYTHON----"
print(str1.rstrip('-'))
str2 = "I love Python"
print(str2.rstrip('n'))
str3 = "    Python    "
print(str3.rstrip())
str4 = "AaBBCCAa"
print(str4.rstrip('Aa'))

Output:

-----PYTHON
I love Pytho
    Python
AaBBCC

Python Strings lstrip() method

The syntax is: strings.lstrip(character)

This method removes only the leading character from strings. The default character is space.

# python strings lstrip() method
str1 = "-----PYTHON----"
print(str1.lstrip('-'))
str2 = "I love Python"
print(str2.lstrip('I'))
str3 = "    Python    "
print(str3.lstrip())
str4 = "AaBBCCAa"
print(str4.lstrip('Aa'))

Output:

PYTHON----
 love Python
Python    
BBCCAa

Python Strings isalnum() method

The syntax is: strings.isalnum()

This method returns True if the provided strings only contain alphabets(a, b,…) and numbers. If the string contains special characters like #, $, %, -,… or space, this method returns False.

# python strings isalnum() method
str1 = "-----PYTHON----"       # contains special characters
print(str1.isalnum())
str2 = "Python"                # contains alphabet only
print(str2.isalnum())
str3 = "23"                    # contains number only
print(str3.isalnum())
str4 = "python123"             # contains alphabet and number together
print(str4.isalnum())
str5 = "Python code"           # contains space also
print(str5.isalnum())

Output:

False
True
True
True
False

Python Strings isalpha() method

The syntax is: strings.isalpha()

This method returns True if the provided strings only contains alphabets(a, b,…). It returns False if the string contains numbers, special characters, or space.

# python strings isalpha() method
str1 = "-----PYTHON----"       # contains special characters
print(str1.isalpha())
str2 = "Python"                # contains alphabet only
print(str2.isalpha())
str3 = "23"                    # contains number only
print(str3.isalpha())
str4 = "python123"             # contains alphabet and number together
print(str4.isalpha())
str5 = "Python code"           # contains space also
print(str5.isalpha())

Output:

False
True
False
False
False

Python Strings isnumeric() method

The syntax is: strings.isnumeric()

This method returns True if the provided strings has only numbers. If the string contains the alphabet, special characters like #, $, %, -,… or space, this method returns False.

# python strings isnumeric() method
str1 = "-----PYTHON----"       # contains special characters
print(str1.isanumeric())
str2 = "Python"                # contains alphabet only
print(str2.isalnum())
str3 = "23"                    # contains number only
print(str3.isalnum())
str4 = "python123"             # contains alphabet and number together
print(str4.isalnum())
str5 = "Python code"           # contains space also
print(str5.isalnum())

Output:

False
True
True
True
False

Python Strings isupper() method

The syntax is: strings.isupper()

This method returns True if the provided strings contains all characters in uppercase otherwise returns False. This method ignores the special characters and spaces present together with uppercase characters and returns True but returns False if only special characters or space is present.

# python strings isupper() method
str1 = "-----PYTHON----"       # special character with uppercase
print(str1.isupper())
str2 = "Python"                # upper and lower together
print(str2.isupper())
str3 = "PYTHON"                # upper only
print(str3.isupper())
str4 = " "                     # contains space only
print(str4.isupper())          
str5 = " P"                    # space and upper
print(str5.isupper())  
str6 = "$%#PYT"                # special characters and upper
print(str6.isupper())

Output:

True
False
True
False
True
True

Python Strings islower() method

The syntax is: strings.islower()

This method returns True if the provided strings contains all characters in lowercase otherwise returns False. This method ignores the special characters and spaces present together with lowercase characters and returns True but returns False if only special characters or space is present.

# python strings islower() method
str1 = "-----python----"       # special character with lowercase
print(str1.islower())
str2 = "Python"                # upper and lower together
print(str2.islower())
str3 = "python"                # lower only
print(str3.islower())
str4 = " "                     # contains space only
print(str4.islower())          
str5 = " p"                    # space and lower
print(str5.islower())  
str6 = "$%#pyt"                # special characters and lower
print(str6.islower())

Output:

True
False
True
False
True
True

Python Strings isspace() method

The syntax is: strings.isspace()

This method returns True if the provided strings contains space only otherwise returns False. This method returns False even if a single character is other than a space.

# python strings isspace() method
str1 = " "              # spaces
print(str1.isspace())
str2 = " p "                # space and other characters
print(str2.isspace())
str3 = "    "                # spaces
print(str3.isspace())
str4 = ""                # empty strings
print(str4.isspace())

Output:

True
False
True
False

Python Strings istitle() method

The syntax is: strings.istitle()

This method returns True if the provided strings contains every first character of a word in uppercase otherwise returns False.

# python strings istitle() method
str1 = "This"              
print(str1.istitle())
str2 = "Good python"                
print(str2.istitle())
str3 = "Good Python"             
print(str3.istitle())
str4 = "I Love Python."               
print(str4.istitle())

Output:

True
False
True
True

Python Strings startswith(value) method

The syntax is: strings.startswith(value)

This method returns True if the provided strings starts with the provided value otherwise returns False.

# python strings startswith() method
str1 = "python"              
print(str1.startswith('py'))
str2 = " Good python"                
print(str2.startswith(" "))
str3 = "###Python"             
print(str3.startswith('##'))
str4 = "python is love."               
print(str4.startswith('python'))

Output:

True
True
True
True

Python Strings endswith(value) method

The syntax is: strings.endswith(value)

This method returns True if the provided strings ends with the provided value otherwise returns False.

# python strings endswith() method
str1 = "python"              
print(str1.endswith('on'))
str2 = " Good python."                
print(str2.endswith("."))
str3 = "###Python  "             
print(str3.endswith(' '))
str4 = "python is love"               
print(str4.endswith('love'))

Output:

True
True
True
True

Sharing is Caring

Leave a Comment

Your email address will not be published. Required fields are marked *