Common Python String Methods

Learn about the common built-in methods used with Python Strings with examples.

Common Python String Methods
Common python string methods

Python has a number of built-in methods that you can use on strings. None of those methods change the original string. They return new strings.

Python String Methods

Here is a list of commonly used Python string methods.

  1. capitalize() - Converts the first character to uppercase
  2. casefold() - Converts string into lower case
  3. center() - Returns a centered string
  4. count() - Returns the number of times a specified value occurs in a string
  5. encode() - Returns an encoded version of the string
  6. endswith() - Returns true if the string ends with the specified value
  7. expandtabs() - Sets the tab size of the string
  8. find() - Searches the string for a specified value and returns the position of where it was found
  9. format() - Formats specified values in a string
  10. format_map() - Formats specified values in a string
  11. index() - Searches the string for a specified value and returns the position of where it was found
  12. isalnum() - Returns True if all characters in the string are alphanumeric
  13. isalpha() - Returns True if all characters in the string are in the alphabet
  14. isdecimal() - Returns True if all characters in the string are decimals
  15. isdigit() - Returns True if all characters in the string are digits
  16. isidentifier() - Returns True if the string is an identifier
  17. islower() - Returns True if all characters in the string are lower case
  18. isnumeric() - Returns True if all characters in the string are numeric
  19. isprintable() - Returns True if all characters in the string are printable
  20. isspace() - Returns True if all characters in the string are white spaces
  21. istitle() - Returns True if the string follows the rules of a title
  22. isupper() - Returns True if all characters in the string are upper case
  23. join() - Joins the elements of an iterable to the end of the string
  24. ljust() - Returns a left-justified version of the string
  25. lower() - Converts a string into lower case
  26. lstrip() - Returns a left trim version of the string
  27. maketrans() - Returns a translation table to be used in translations
  28. partition() - Returns a tuple where the string is parted into three parts
  29. replace() - Returns a string where a specified value is replaced with a specified value
  30. rfind() - Searches the string for a specified value and returns the last position of where it was found
  31. rindex() - Searches the string for a specified value and returns the last position of where it was found
  32. rjust() - Returns a right justified version of the string
  33. rpartition() - Returns a tuple where the string is parted into three parts
  34. rsplit() - Splits the string at the specified separator, and returns a list
  35. rstrip() - Returns a right trim version of the string
  36. split() - Splits the string at the specified separator, and returns a list
  37. splitlines() - Splits the string at line breaks and returns a list
  38. startswith() - Returns true if the string starts with the specified value
  39. strip() - Returns a trimmed version of the string
  40. swapcase() - Swaps cases, lower case becomes upper case and vice versa
  41. title() - Converts the first character of each word to upper case
  42. translate() - Returns a translated string
  43. upper() - Converts a string into upper case
  44. zfill() - Fills the string with a specified number of 0f values at the beginning

Capitalize

The capitalize() method in Python returns a copy of the string with only the first character capitalized.

Code

str1 = "pylenin writes about python." 
print(str1.capitalize())

Output

Pylenin writes about python.

If you want to capitalize the first letter of every word, check out the code below.

Code

str1 = "pylenin writes about python." 
str_list = str1.split(" ") 
new_string = ' '.join(x.capitalize() for x in str_list) 
print(new_string)

Output

Pylenin Writes About Python.

Check out other commonly used Python string methods.


Casefold

The casefold() method in Python returns a case folded copy of a string where all characters are lowercase.

Code

str1 = "Pylenin writes about Python." 
print(str1.casefold())

Output

pylenin writes about python.

The casefold() method is similar to lower() method. However, it is more aggressive.

casefold() method is best suited for caseless matching.

What is Caseless Matching?

Caseless Matching is a way of erasing case differences in strings by mapping characters of different cases to a single form.

For example, the German lowercase letter ß is equivalent to ss.

Let's look at the example below.

Code

str1 = "Pylenin has a nice dress."
str2 = "Pylenin has a nice dreß." 

# Experiment with lower()
print(str1.lower() == str2.lower()) 

# Experiment with casefold
print(str1.casefold() == str2.casefold())

Output

False 
True

While the lower() method was unable to convert the German character, casefold() method converted it successfully and hence showed that both the strings are the same.

Check out other commonly used Python string methods.


Center

The center() method in Python will align the string to the center, using a specified character(by default, it is space) as the fill character.

Syntax

string.center(length, character)

length - The length of the required string(Required)
character - The fill character for the missing space(Optional).
            By default is space.

Example 1

Code

str1 = "Pylenin"

str2 = str1.center(10)

print(str2)

print(f"Str1 length was {len(str1)}")
print(f"Str2 length is {len(str2)}")

Output

 Pylenin  
Str1 length was 7
Str2 length is 10

The length of the new string has become 10. The increase in length was due to addition of space characters to the original string.

Example 2

Code

str1 = "Pylenin"

str2 = str1.center(10, '*')

print(str2)

print(f"Str1 length was {len(str1)}")
print(f"Str2 length is {len(str2)}")

Output

*Pylenin**
Str1 length was 7
Str2 length is 10

By providing the optional character parameter, you can see how the new string has changed.

Example 3 - Printing Pyramid Patterns in Python

You can do many exciting things with center() method in Python. For example - Constructing a Pyramid.

Code

for i in range(1, 10, 2):
    x = i*'*'
    print(x.center(10))

Output

    *     
   ***    
  *****   
 *******  
********* 

Check out other commonly used Python string methods.


Count

The count() method returns the number of times a substring s1 appears in the string s2. It is not case sensitive.

Syntax

string.count(value, start, end) 

value:	The substring to search for(Required) 
start:	The integer position to start the search. Default is 0.(Optional) 
end:	The integer position to end the search. Default is the end of the   
        string.(Optional)

Example 1

Code

s2 = "I like Pylenin"
s1 = 'like' 

if s2.count(s1) > 0: 
    print(f"'{s1}' exists in '{s2}'")

Output

'like' exists in 'I like Pylenin'

Example 2 - Check for case sensitivity

Code

s2 = "I like Pylenin"
s1 = 'Like' 
if s2.count(s1) > 0: 
    print(f"'{s1}' exists in '{s2}'") 
else: 
    print(f"'{s1}' does not exist in '{s2}'")

Output

'Like' does not exist in 'I like Pylenin'

Example 3 - Search for a non-existing string

Code

s2 = "I like Pylenin"
s1 = 'Python' 
if s2.count(s1) > 0: 
    print(f"'{s1}' exists in '{s2}'") 
else: 
    print(f"'{s1}' doesn't exist in '{s2}'")

Output

'Python' doesn't exist in 'I like Pylenin'

Example 4 - Search for a substring in a specific portion of another string

Code

s2 = "I like reading Pylenin blogs on Python"
s1 = 'Python' 

# Search between position 10 and 20
if s2.count(s1, 10, 20) > 0: 
    print(f"'{s1}' exists in '{s2}'") 
else: 
    print(f"'{s1}' doesn't exist in '{s2}'") 

print(s2.find(s1))

Output

As you can see, the substring Python doesn't occur between the positions 10 and 20. The find() method shows that it occurs at position 32.

Check out other commonly used Python string methods.


Encode

The encode() method in Python encodes a string using the specified encoding. If no encoding is specified, UTF-8 encoding will be used.

Syntax of encode() method

string.encode(encoding, errors) 

encoding: Encoding to use(optional) 
          Default value is UTF-8. 
errors:	Required Error method(Optional)

Check out the list of standard encodings with Python.

You can use the following error values.

  1. backslashreplace - use a backslash instead of the character that could not be encoded
  2. ignore - ignore the characters that cannot be encoded.
  3. namereplace - replace the character with a text explaining the character.
  4. strict - Default, will raise an error on failure.
  5. replace - replace the character with a question mark.
  6. xmlcharrefreplace - replace the character with an xml character.

Python is only going to use these above error types, if it runs into some error while encoding.

Example 1 - Simple encoding to UTF-8

Code

str1 = "I like Pylenin" print(str1.encode())

Output

b'I like Pylenin'

Example 2 - Encoding a Non-ASCII string to ASCII

Code

str1 = "Pylenin like äpples" 
print(str1.encode('ASCII', errors='backslashreplace'))
print(str1.encode('ASCII', errors='ignore')) 
print(str1.encode('ASCII', errors='namereplace'))
print(str1.encode('ASCII', errors='replace')) 
print(str1.encode('ASCII', errors='xmlcharrefreplace'))

Output

b'Pylenin like \\xe4pples'
b'Pylenin like pples'
b'Pylenin like \\N{LATIN SMALL LETTER A WITH DIAERESIS}pples'
b'Pylenin like ?pples'
b'Pylenin like äpples'

Check out other commonly used Python string methods.


Endswith

The endswith() method in Python returns True if the string ends with the specified value, otherwise, returns False. It is not case sensitive.

Syntax of endswith() method

string.endswith(value, start, end) 

value: Value to check if the string endswith(Required) 
start: The integer position to start the search. Default is 0.(Optional)
end:   The integer position to end the search. Default is the end of the 
       string.(Optional)

Example 1

Code

str1 = "Pylenin makes videos on Python" 

print(str1.endswith('Python')) 
print(str1.endswith('videos'))

Output

True 
False

Example 2 - Check for case sensitivity

Code

str1 = "Pylenin makes videos on Python" 
print(str1.endswith('python'))

Output

False

Example 3 - Check within specified positions of a string

Code

str1 = "Pylenin makes videos on Python" 

# Check between position 5 and 10
print(str1.endswith('Python', 5, 10)) 

print(f"It occurs at position - {str1.find('Python')}")

Output

False 
It occurs at position - 24

Check out other commonly used Python string methods.


Expandtabs

The expandtabs() method in Python, sets the tabsize to the specified number of characters for every occurence of \t. Default is 8.

Syntax of expandtabs() method

string.expandtabs(tabsize) 

tabsize: A positive integer specifying the tabsize. Default tabsize is 8

Tab positions occur every tabsize character. Default is 8, giving tab positions at columns 0, 8, 16 and so on.

Example

Code

str1 = "Pylenin\tloves\tPython"
print(str1) 

str2 = str1.expandtabs(8) #Default
print(str2) 
str3 = str1.expandtabs(10) 
print(str3)

Output

Pylenin	loves	Python 
Pylenin loves   Python 
Pylenin             loves               Python

Check out other commonly used Python string methods.


Find

The find() method is similar to the index() method. Only difference - index() method raises an exception if the value is not found.

It is not case sensitive.

Syntax of find() method

string.find(value, start, end) 
value:	The value to search for(Required) 
start:	The integer position to start the search. Default is 0.(Optional)
end:	The integer position to end the search. Default is the end of the 
        string.(Optional)

Example 1

Code

s2 = 'I like Pylenin'
s1 = 'like' 

print(s2.find(s1))

Output

2

The above result tells us that the like substring first occurs at 2nd index.

Example 2

Code

s2 = 'I like Pylenin'
s1 = 'Python' 

print(s2.find(s1))

Output

-1

The above result tells us that the substring Python doesn't exist in s1.

Example 3 - Check for case sensitivity

Code

s2 = 'I like Pylenin'
s1 = 'pylenin' 

print(s2.find(s1))

Output

-1

Check out other commonly used Python string methods.


Format Map

Difference between format() and format_map() in Python

The format_map() method is similar to format() method in Python, except that it only accepts a dictionary as input.

Learn more about Python String format() method.

Syntax of format_map() method

string.format_map(mapping) 

mapping: The Input dictionary

Example 1

Code

s = '{name} lives in {country}' 
my_dict = {'name': 'Pylenin', 'country': 'India'} 

# Using format_map() method
print(s.format_map(my_dict)) 

# Using format() method
print(s.format(**my_dict))

Output

Pylenin lives in India 
Pylenin lives in India

Example 2 - If mapping has more keys

If mapping dictionary has more keys, then only the necessary keys are used for string formatting.

Code

s = '{name} lives in {country}' 
my_dict = {'name': 'Pylenin', 'country': 'India', 'language': 'Python'} 

# Using format_map() method
print(s.format_map(my_dict)) 

# Using format() method
print(s.format(**my_dict))

Output

Pylenin lives in India 
Pylenin lives in India

Example 3 - If mapping has missing keys

If mapping dictionary has missing keys, both format() and format_map() will throw a KeyError.

Code

s = '{name} lives in {country}' 
my_dict = {'name': 'Pylenin'} 

# Using format_map() method
print(s.format_map(my_dict)) 

# Using format() method
print(s.format(**my_dict))

Output

# format_map()
KeyError: 'country' 

# format()
KeyError: 'country'

Advantage of format_map() over format()

With the format_map() method, you can avoid such KeyError issues by working with a dict subclass.

Let's look at the below example.

Code

class PyleninDict(dict): 
    def __missing__(self, key): 
        return '{}' 

s = '{name} is born in {country}'
my_dict = PyleninDict(name='Pylenin') 
print(s.format_map(my_dict))

Output

Pylenin is born in {}

As you can see, we didn't receive a KeyError anymore. format_map() was able to handle the missing key.

The above doesn't work for format() method

Code

class PyleninDict(dict): 
    def __missing__(self, key): 
        return '{}' 
        
s = '{name} is born in {country}'
my_dict = PyleninDict(name='Pylenin') 

# Using format() instead of format_map()
print(s.format(**my_dict))

Output

KeyError: 'country'

Check out other commonly used Python string methods.


Index

Difference between index() and find() in Python

Similar to find() method in Python, the index() method finds the first occurence of a certain value.

If the value is not found, it raises a ValueError exception. The find() method in Python on the other hand, returns -1, if the value is not found.

The index() method is not case sensitive.

Syntax of index() method

string.index(value, start end) 

value:	The value to search for(Required) 
start:	The integer position to start the search. Default is 0.(Optional)
end:	The integer position to end the search. Default is the end of the string.(Optional)

Example 1

Code

str1 = "Pylenin loves Python" 
print(str1.index("Python"))

Output

14

The substring Python occurs first time at position 14 in the string.

Example 2 - Check for case sensitivity

Code

str1 = "Pylenin loves Python"
print(str1.index("python"))

Output

ValueError: substring not found

Example 3 - Search for a non-existing string

Code

str1 = "Pylenin loves Python" 
print(str1.index("Apples"))

Output

ValueError: substring not found

Example 4 - Search a substring s1 in a specific portion of string s2

Code

s2 = 'I like reading Pylenin blogs on Python'
s1 = 'Python' 

# Search between position 10 and 20
try: 
    print(s2.index(s1, 10, 20)) 
except Exception as e: 
    print(e.__class__, e) 
    print(f"'{s1}' occurs at index {s2.index(s1)}")

Output

<class 'ValueError'> substring not found 
'Python' occurs at index 32

As you can see, the substring Python occurs at index 32, but we were searching within the index 10 and 20.

Because, we are using a try-except block, ValueError exception is not being raised. Learn more about Python Exceptions and ways to handle them.

Check out other commonly used Python string methods.


Isalnum

The isalnum() method in Python returns True if all characters in the string are alphanumeric.

Alphanumeric characters - Alphabet letters (a-z) and numbers (0-9)

Syntax of isalnum() method

string.isalnum() - Returns True or False

Example 1

Code

s1 = "Pylenin1992" 
print(s1.isalnum())

Output

True

Example 2 - Check for a sentence

Code

s1 = "Pylenin was born in 1992" 
print(s1.isalnum())

Output

False

Example 3 - Check for special characters

Code

s1 = "pylenin1992@gmail.com" 
print(s1.isalnum())

Output

False

As you can see, @ is not an alphanumeric character.

Example 4 - Check for random characters

Code

s1 = "!#%&?" 
print(s1.isalnum())

Output

False

Check out other commonly used Python string methods.


Isalpha

The isalpha() method in Python returns True, if all characters are alphabets(a-z).

Syntax of isalpha() method

string.isalpha() 
Returns True or False

Example 1

Code

s1 = "Pylenin" 
print(s1.isalpha())

Output

True

Example 2 - Check for a sentence

Code

s1 = "Pylenin was born in 1992" 
print(s1.isalpha())

Output

False

Example 3 - Check for special characters

Code

s1 = "pylenin1992@gmail.com" 
print(s1.isalpha())

Output

False

As you can see, @ is not an alphabetic character.

Example 4 - Check for random characters

Code

s1 = "!#%&?" 
print(s1.isalpha())

Output

False

Check out other commonly used Python string methods.


Isdecimal

The isdecimal() method in Python returns True if all the characters in the string are decimal characters. For empty strings, it returns False.

What are Decimal characters?

Any character that can be used to form a number in base 10, is a decimal character.

Example:-

  1. All numbers from 0 to 9
  2. All numbers from 0 to 9 in various languages like Arabic Indic, Devnagri etc.

You can find all the decimal characters in Unicode General Category Nd.

Syntax of isdecimal() method

string.isdecimal() - Returns True or False

Example

Code/Output

s = "1992"
print(s.isdecimal()) 
>>> True 

# Floating point number
s = "1992.10"
print(s.isdecimal()) 
>>> False 

# contains alphabets
s = "Pylenin1992"
print(s.isdecimal()) 
>>> False 

# contains alphabets and spaces
s = "Pylenin loves Python"
print(s.isdecimal()) 
>>> False 

# Empty string
s = ''
print(s.isdecimal()) 
>>> False 

# superscripts
s = '1992\u00B2'
print(s) 
>>> 1992 ^ 2
print(s.isdecimal()) 
>>> False 

# fractions
s = '\u00BD'
print(s)
>>> 1/2
print(s.isdecimal()) 
>>> False

Difference between isdigit() and isdecimal()

Difference between the above methods crop up with various unicode characters, such as superscripts.

Code

# superscripts
s = '2345\u00B2'
print(s) 
print(s.isdecimal()) 
print(s.isdigit())

Output

2345^2 
False #isdecimal()
True #isdigit()

Check out other commonly used Python string methods.


Isdigit()

The isdigit() method in Python, returns True if all characters are numerical digits. Exponents are also considered digits.

Syntax of isdigit() method

string.isdigit() - Returns True or False

Example

Code/Output

s = "1992"
print(s.isdigit()) 
>>> True 

# Floating point number
s = "1992.10"
print(s.isdigit()) 
>>> False 

# contains alphabets
s = "Pylenin1992"
print(s.isdigit()) 
>>> False 

# contains alphabets and spaces
s = "Pylenin loves Python"
print(s.isdigit()) 
>>> False 

# Empty string
s = ''
print(s.isdigit()) 
>>> False 

# superscripts
s = '1992\u00B2'
print(s) 
>>> 1992^2
print(s.isdigit()) 
>>> True

# fractions
s = '\u00BD'
print(s) 
>>> 1/2
print(s.isdigit()) 
>>> False

As you can see, fractions don't qualify as digits.

Check out other commonly used Python string methods.


Isidentifier()

The isidentifier() method in Python returns True, if the string is a valid identifier.

What is a valid identifier in Python?

  1. Should contain alphanumeric characters - (a-z) and (0-9).
  2. Can have underscores (_).
  3. Shouldn't contain spaces.
  4. Cannot start with a number.

Syntax of isidentifier() method

string.isidentifier() - Returns True or False

Example 1

Code/Output

# only alphabets
str1 = "Pylenin"
print(str1.isidentifier()) 
>>> True 

# Only numbers
str2 = "1992"
print(str2.isidentifier()) 
>>> False 

# alphanumeric characters
str3 = "Pylenin1992"
print(str3.isidentifier()) 
>>> True 

# alphanumeric characters starting with numbers
str4 = "1992Pylenin"
print(str4.isidentifier()) 

# special characters like '@'
str5 = "pylenin1992@gmail.com"
print(str5.isidentifier()) 
>>> False 

# sentences
str6 = "Pylenin loves Python"
print(str6.isidentifier()) 
>>> False

As you can see, the isidentifier() method in Python returns False even for numerical strings.

Example 2 - Working with underscores

Code/Output

# underscores
str1 = "_"
print(str1.isidentifier()) 
>>> True 

# alphabets with underscores
str2 = "Pylenin_loves_Python"
print(str2.isidentifier()) 
>>> True 

# numbers with underscores
str3 = "1234_5678_90"
print(str3.isidentifier()) 
>>> False 

# alphanumeric with underscores
str4 = "Pylenin_1992"
print(str4.isidentifier()) 
>>> True

Check out other commonly used Python string methods.


Islower()

The islower() method in Python returns True, if all characters are lowercase.

It doesn't take numbers, symbols and spaces into account.

Syntax of islower() method

string.islower() - Returns True or False

Example

Code/Output

# all lowercase alphabets
s = "pylenin"
print(s.islower()) 
>>> True 

# lowercase alphabets with numbers
s = "pylenin1992"
print(s.islower()) 
>>> True 

# lowercase alphabets with spaces
s = "pylenin loves python"
print(s.islower()) 
>>> True 

# lowercase alphabets with special symbols
s = "https://www.youtube.com/pylenin"
print(s.islower()) 
>>> True 

# string containing uppercase characters
s = "Pylenin loves python"
print(s.islower()) 
>>> False

The islower() method in Python doesn't make changes to the original string. It actually returns a new string.

You can confirm this by using the id() function in Python. It is a built-in function in Python that returns the unique identity of an object.

Code/Output

s1 = "pylenin"
s2 = "pylenin" 

print(id(s1) == id(s2)) 
>>> True 

print(id(s1) == id(s1.islower())) 
>>> False 

print(id(s2) == id(s2.islower())) 
>>> False

Check out other commonly used Python string methods.


Isnumeric()

The isnumeric() method in Python returns True, if all characters are numeric (0-9).

What are numerical characters in Python?

The following characters are considered numerical in Python

  1. Decimal characters (like: 0, 1, 2 etc.)
  2. subscript and superscript
  3. Characters having Unicode numeric value property (e.g. fractions, roman numerals, currency numerators)

Note:-

  1. Negative integers like -1 are not numerical as the - symbol is not numeric.
  2. Floats like 2.3 are not numerical as . is not a numeric character.

Syntax of isnumeric() method

string.isnumeric() - Returns True or False

Example

Code/Output

# string with integers
s = '1992'
print(s.isnumeric())
>>> True

# negative integer
s = '-1992'
print(s.isnumeric())
>>> False

# Unicode
s = '\u0660'
print(s.isnumeric())
>>> True

# alphanumeric
s='pylenin1992'
print(s.isnumeric())
>>> False

Check out other commonly used Python string methods.


Isprintable()

The isprintable() method in Python returns True, if all characters are printable. Carriage return (\r), line feed (\n) and tabs(\t) are examples of non printable characters in Python.

Syntax of isprintable() method

string.isprintable() - Returns True or False

Example

Code/Output

str1 = "\r"
print(str1.isprintable()) 
>>> False 

str2 = "\n"
print(str2.isprintable()) 
>>> False 

str3 = "\t"
print(str3.isprintable()) 
>>> False 

str4 = "https://youtube.com/pylenin"
print(str4.isprintable()) 
>>> True

Check out other commonly used Python string methods.


Isspace()

The isspace() method in Python returns True if all characters in your string are whitespaces. If the string contains one or more non-white space characters, it returns False.

Each of the following characters are considered whitespace.

  1. Empty space
  2. \n - Newline
  3. \r - Carriage return
  4. \f - feed
  5. \t - Horizontal tab
  6. \v - Vertical Tab

Syntax of isspace() method

string.isspace() - Returns True or False

Example

Code/Output

s = " "
print(s.isspace()) 
>>> True 

s = "\n"
print(s.isspace()) 
>>> True 

s = "\r"
print(s.isspace()) 
>>> True 

s = "\t"
print(s.isspace()) 
>>> True 

s = "\v"
print(s.isspace()) 
>>> True 

s = "\f"
print(s.isspace()) 
>>> True 

s = "\n \r \f"
print(s.isspace()) 
>>> True 

s = "Pylenin"
print(s.isspace()) 
>>> False

Check out other commonly used Python string methods.


Istitle()

The istitle() method in Python returns True if all words in the string start with an upper case letter, and the rest of the letters are lower case letters, otherwise False.

Symbols and numbers are ignored.

Syntax of istitle() method

string.istitle() - Returns True or False

Example

s = "Hello, I Am Pylenin"
print(s.istitle()) 
>>> True 

s = "Lenin Mishra"
print(s.istitle()) 
>>> True 

s = "1992 Pylenin"
print(s.istitle()) 
>>> True

Check out other commonly used Python string methods.


Isupper()

The isupper() method in Python returns True if all the characters are in upper case.

Only alphabet characters are taken into consideration. Numbers, symbols and spaces are not checked.

Syntax of isupper() method

string.isupper() - Returns True or False

Example

s = "HELLO, I AM PYLENIN"
print(s.isupper()) 
>>> True 

s = "123456"
print(s.isupper()) 
>>> False 

s = "I AM 29 YEARS old"
print(s.isupper()) 
>>> False

Check out other commonly used Python string methods.


Join

The join() method in Python returns a string in which all the elements of an iterable have been joined by the provided string separator.

If the iterable contains any non-string values, it raises a TypeError exception.

Syntax of join() method

separator.join(iterable) 

iterable:	Any iterable object where all the values are strings.

List, Tuple, String, Dictionary and Sets - all qualify as iterables for the join() method.

Example 1

Code/Output

# list
x = ["Pylenin", "loves", "Python"] 
sep = " "print(sep.join(x)) 
>>> Pylenin loves Python 

# dictionary
x = {"name": "Pylenin", "language":"Python"} 
sep = "-"print(sep.join(x.values())) 
>>> Pylenin-Python 

# dictionary
x = {"name": "Pylenin", "language":"Python"} 
sep = " loves "
print(sep.join(x.values())) 
>>> Pylenin loves Python 

# tuple
x = ("p", "y", "l", "e", "n", "i", "n") 
sep =""
print(sep.join(x)) 
>>> pylenin 

# sets
x = {"1", "2", "3", "3"} 
sep ="-"
print(sep.join(x)) 
>>> 1-3-2

Can you explain why the join() method for sets, doesn't return both the 3 in the final string? .

Example 2 - TypeError Exception with join() method

If any of the elements of the iterable are not string, Python will return a TypeError exception.

Code/Output

x = ["Pylenin", "eats", 12, "apples"] 
sep = " "
print(sep.join(x)) 
>>> TypeError: sequence item 2: expected str instance, int found

You can fix it by using list comprehension and converting elements to a string first hand.

Code/Output

x = ["Pylenin", "eats", 12, "apples"] 
sep = " "
print(sep.join([str(y) for y in x])) 
>>> Pylenin eats 12 apples

Check out other commonly used Python string methods.


ljust()

The ljust() method in Python left aligns the string, using a specific number of characters (space is used as default) as the provided fill character.

Syntax of ljust() method

Example 1

Code

x = "Pylenin"
y = x.ljust(20) 

print(len(y)) 
print(y)

Output

20 
Pylenin

As you can see, the length of the new string is 20 characters long.

Example 2 - Using a different fill character

Code

x = "Pylenin"
y = x.ljust(20, "*") 
print(len(y)) 
print(y)

Output

20 
Pylenin*************

Check out other commonly used Python string methods.


lower()

The lower() method in Python returns a string with all characters converted to lowercase.

Symbols and numbers are ignored.

Syntax of lower() method

string.lower() - Returns a new string

Example

Code/Output

x = "Pylenin loves Python"
print(x.lower()) 
>>> pylenin loves python 

x = "Pylenin1992@gmail.com"
print(x.lower()) 
>>> pylenin1992@gmail.com

Check out other commonly used Python string methods.


lstrip()

The lstrip() method in Python, returns a new string by removing(stripping) all the characters from the left that are passed as string argument. If no arguments are passed, it removes the leading spaces

Syntax of lstrip() method

string.lstrip() - Returns a new string

Example

Code/Output

x = "  Pylenin loves Python"
print(x.lstrip()) 
>>> Pylenin loves Python 

x = "*Pylenin loves Python*"
print(x.lstrip('*')) 
>>> Pylenin loves Python* 

x = "*@Pylenin loves Python@*"
print(x.lstrip('@')) 
>>> *@Pylenin loves Python@*

As you can see, the lstrip() method didn't work on the third string. The @ has to be leading in order to be stripped.

Check out other commonly used Python string methods.


Maketrans()

The maketrans() method in Python is used to specify the list of characters that need to be replaced or deleted in the whole string.

It returns a translation table that can be used with the translate() method.

Syntax of maketrans() method

string.maketrans(str1, str2, str3) 

str1 : Specifies the list of characters that need to be replaced. 
str2 : Specifies the list of characters with which the characters need to be replaced. 
str3 : Specifies the list of characters that need to be deleted.

Example 1

Code

str1 = "Pylenin" 
table = str1.maketrans("n", "m") 
print(str1.translate(table))

Output

Pylemim

As you can see, all instances of n were replaced with m.

Example 2 - Using a dictionary with maketrans()

Code

mapping_dict = {"n":"m"} 
str1 = "Pylenin" 
table = str1.maketrans(mapping_dict) 
print(str1.translate(table))

Output

Pylemim

Example 3 - How to remove characters with maketrans()

Code

str1 = "Pylenin?" 
table = str1.maketrans("","","?") 
print(str1.translate(table))

Output

Pylenin

Since the 3rd argument is used to pass in the characters to be removed, the first 2 arguments are being left empty above.

We can achieve the same result by passing in a dictionary.

Code

mapping_dict= {"?":None} 
str1 = "Pylenin?" 
table = str1.maketrans(mapping_dict) 
print(str1.translate(table))

Output

Pylenin

Just use None as values for characters you want removed from your string.

Check out other commonly used Python string methods.


partition()

The partition() method in Python searches for the first occurence of the specified string and splits the string into a tuple containing three elements.

  1. The first element  - Contains the part before the specified string.
  2. The second element - Contains the specified string.
  3. The third element - Contains the part after the string.

Syntax of partition() method

string.partition(value) 

value: The substring to partition on

Example 1

Code

str1 = "Pylenin loves Python"
print(str1.partition("loves"))

Output

('Pylenin ', 'loves', ' Python')

Example 2 - When the substring doesn't exist

Code

str1 = "Pylenin loves Python"
print(str1.partition("cake"))

Output

('Pylenin loves Python', '', '')

As you can see, it returned the entire string as first element of the tuple and the last 2 elements are empty strings. The partition() method doesn't throw any error if it is unable to find the substring.

Example 3 - When the substring occurs multiple times

Code

str1 = "Pylenin loves Python and Python loves Pylenin"
print(str1.partition("Python"))

Output

('Pylenin loves ', 'Python', ' and Python loves Pylenin')

The partition() method separates at the first occurence of the provided substring.

Check out other commonly used Python string methods.


Replace()

The replace() method in Python replaces a specified substring with another substring.

It's not case sensitive.

Syntax of replace() method

string.replace(old_value, new_value, count) 

old_value: The substring to be replaced(required) 
new_value: The substring to replace with(required) 
count: A number specifying the number of occurences of old_value to 
       replace. (Optional) If nothing is mentioned, all occurences are 
       replaced.

Example 1

Code/Output

str1 = "Pylenin loves Python"
print(str1.replace("Python","Apples")) 
>>> Pylenin loves Apples 

# replacing a non-existing substring
str1 = "Pylenin loves Python"
print(str1.replace("mangoes","Apples")) 
>>> Pylenin loves Python 

# check for case sensitivity
str1 = "Pylenin loves Python"
print(str1.replace("python","Apples")) 
>>> Pylenin loves Python

Example 2 - Changing multiple occurences of a substring

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin"
print(str1.replace("Python","Apples", 1)) 
>>> Pylenin loves Apples and Python loves Pylenin

As you see, only the first occurence of Python is changed to Apples.

Check out other commonly used Python string methods.


rfind()

The rfind() method in Python finds the last occurrence of the specified substring. It returns -1 if the value is not found.

Its the opposite of find() method as it finds the first occurence of a substring.

Syntax of rfind() method

string.rfind(value, start, end) 
value: The substring to find(required) 
start:	The integer position to start the search. Default is 0.(Optional)
end:	The integer position to end the search. Default is the end of the 
        string.(Optional)

Example

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin." 

# first occurence of "Python"
print(str1.find("Python")) 
>>> 14 

# last occurence of "Python"
print(str1.rfind("Python")) 
>>> 25

Example 2 - A substring that doesn't exist

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin."
print(str1.rfind("Apples")) 
>>> -1

Example 3 - Last occurence of substring between specified positions

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin." 

# occurence of "Python" between 
# position 20 and 40
print(str1.rfind("Python", 20, 40)) 
>>> 25

Check out other commonly used Python string methods.


rindex()

The rindex() method finds the last occurrence of the specified substring. If the value is not found, rindex() method raises a ValueError exception.

Its the opposite of index() method as it finds the position of first occurence of a substring.

Syntax of rindex() method

string.rindex(value, start, end) 

value: The substring to find(required) 
start:	The integer position to start the search. Default is 0.(Optional)
end:	The integer position to end the search. Default is the end of the
        string.(Optional)

Example

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin." 

# first occurence of "Python"
print(str1.index("Python")) 
>>> 14 

# last occurence of "Python"
print(str1.rindex("Python")) 
>>> 25

Example 2 - A substring that doesn't exist

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin."
print(str1.rindex("Apples")) 
>>> ValueError: substring not found

Example 3 - Last occurence of substring between specified positions

Code/Output

str1 = "Pylenin loves Python and Python loves Pylenin." 

# occurence of "Python" between 
# position 20 and 40
print(str1.rindex("Python", 20, 40)) 
>>> 25

Check out other commonly used Python string methods.


rjust()

The rjust() method in Python right aligns the string, using a specific number of characters (space is used as default) as the provided fill character.

Syntax of rjust() method

string.rjust(length, fill_character) 
length:         The length of the output string(Required). 
fill_character: A character to fill the missing space to the left of the
                string(Optional). Default is space.

Example 1

Code

x = "Pylenin"
y = x.rjust(20) 
print(len(y)) 
print(y)

Output

20 
Pylenin

As you can see, the length of the new string is 20 characters long.

Example 2 - Using a different fill character

Code

x = "Pylenin"
y = x.rjust(20, "*") 
print(len(y)) 
print(y)

Output

20 
*************Pylenin

Check out other commonly used Python string methods.


rpartition()

The rpartition() method in Python searches for the last occurence of the specified string and splits the string into a tuple containing three elements.

  1. The first element  - Contains the part before the specified string.
  2. The second element - Contains the specified string.
  3. The third element - Contains the part after the string.

Syntax of rpartition() method

string.rpartition(value) 

value: The substring to partition on

Example 1

Code

str1 = "Pylenin loves Python"
print(str1.rpartition("loves"))

Output

('Pylenin ', 'loves', ' Python')

Example 2 - When the substring doesn't exist

Code

str1 = "Pylenin loves Python"
print(str1.rpartition("cake"))

Output

('', '', 'Pylenin loves Python')

As you can see, it returned the entire string as the last element of the tuple and the first 2 elements are empty strings. The rpartition() method doesn't throw any error if it is unable to find the substring.

Example 3 - When the substring occurs multiple times

Code

str1 = "Pylenin loves Python and Python loves Pylenin"
print(str1.rpartition("Python"))

Output

('Pylenin loves Python and ', 'Python', ' loves Pylenin')

The rpartition() method separates at the last occurence of the provided substring.

Check out other commonly used Python string methods.


rsplit()

The rsplit() method in Python splits a string into a list, starting from the right.

If no maxsplit parameter is specified, this method will return the same as the split() method.

When maxsplit is specified, the list will contain the specified number of elements plus one.

Syntax of rsplit() method

string.rsplit(separator, maxsplit) 
separator: Specifies the separator to use when splitting the 
           string(Optional). By default any whitespace is a separator
maxsplit:  Specifies how many splits to do(Optional). Default value is -1, 
           which is "all occurrences"

Example

Code/Output

str1 = "Pylenin loves Python"
print(str1.rsplit()) 
>>> ['Pylenin', 'loves', 'Python'] 

# Using the maxsplit parameter
str1 = "Pylenin loves Python"
print(str1.rsplit(" ", 1)) 
>>> ['Pylenin loves', 'Python'] 

str1 = "Pylenin loves Python"
print(str1.rsplit("loves", 1)) 
>>> ['Pylenin ', ' Python']

Check out other commonly used Python string methods.


rstrip()

The rstrip() method in Python, returns a new string by removing(stripping) all the characters from the right that are passed as string argument. If no arguments are passed, it removes the trailing spaces

Syntax of rstrip() method

string.rstrip() - Returns a new string

Example

Code/Output

x = "Pylenin loves Python   "
print(x.rstrip()) 
>>> Pylenin loves Python 

x = "*Pylenin loves Python*"
print(x.rstrip('*')) 
>>> *Pylenin loves Python 

x = "*@Pylenin loves Python@*"
print(x.rstrip('@')) 
>>> *@Pylenin loves Python@*

As you can see, the rstrip() method didn't work on the third string. The @ has to be trailing in order to be stripped.

Check out other commonly used Python string methods.


split()

The split() method in Python splits a string into a list, starting from the left.

When maxsplit is specified, the list will contain the specified number of elements plus one.

Syntax of split() method

string.split(separator, maxsplit) 

separator: Specifies the separator to use when splitting the 
           string(Optional). By default any whitespace is a separator 
maxsplit:  Specifies how many splits to do(Optional). Default value is -1,
           which is "all occurrences"

Example

Code/Output

str1 = "Pylenin loves Python"
print(str1.split()) 
>>> ['Pylenin', 'loves', 'Python'] 

# Using the maxsplit parameter
str1 = "Pylenin loves Python"
print(str1.split(" ", 1)) 
>>> ['Pylenin', 'loves Python'] 

str1 = "Pylenin loves Python"
print(str1.split("loves", 1)) 
>>> ['Pylenin ', ' Python']

Check out other commonly used Python string methods.


splitlines()

The splitlines() method in Python splits the string at line breaks and returns a list of lines in the string.

The following symbols are considered as line breaks for splitlines().

  1. \n - Line Feed
  2. \r - Carriage Return
  3. \r\n - Carriage Return and Line Feed
  4. \v - Line Tabulation
  5. \f- Form Feed

Syntax of splitlines() method

string.splitlines(keepends) 

keepends: Specifies if the line breaks should be included - True or False(Optional) 
Default value is False.

Example

Code/Output

str1 = "Pylenin loves Python.\nHe also likes Apples."
print(str1.splitlines()) 
>>> ['Pylenin loves Python.', 'He also likes Apples.'] 

str1 = "Pylenin loves Python.\nHe also likes Apples."
print(str1.splitlines(True)) 
>>> ['Pylenin loves Python.\n', 'He also likes Apples.'] 

str1 = "Pylenin\rPython\nApples\r\nBlogs\vYoutube\f"
print(str1.splitlines()) 
>>> ['Pylenin', 'Python', 'Apples', 'Blogs', 'Youtube'] 

str1 = "Pylenin\rPython\nApples\r\nBlogs\vYoutube\f"
print(str1.splitlines(True)) 
>>> ['Pylenin\r', 'Python\n', 'Apples\r\n', 'Blogs\x0b', 'Youtube\x0c']

Check out other commonly used Python string methods.


startswith()

The startswith() method in Python returns True if the string starts with the specified value, otherwise it returns False. The startswith() method is not case sensitive.

Syntax of startswith() method

string.startswith(value, start, end) 

value:	The substring to search for(Required) 
start:	The integer position to start the search. Default is 0.(Optional)
end:	The integer position to end the search. Default is the end of the string.(Optional)

Example 1

Code

str1 = "Pylenin loves Python" 
print(str1.startswith("Pylenin"))

Output

True

The string does starts with substring Pylenin.

Example 2 - Check for case sensitivity

Code

str1 = "Pylenin loves Python" 
print(str1.startswith("pylenin"))

Output

False

Example 3 - Search for a different string

Code

str1 = "Pylenin loves Python" 
print(str1.startswith("Python"))

Output

False

Example 4 - Check if string s1 starts with substring s2 within a specific position

Code

s1 = 'I like reading Pylenin blogs on Python'
s2 = 'Pylenin' 

# Search between position 15 and 30
print(s1.startswith(s2, 15, 30))

Output

True

As you can see, the substring Python occurs at position 15. Hence, the startswith() method returns True when searched between position 15 and 30.

Check out other commonly used Python string methods.


strip()

The strip() method in Python, returns a new string by removing(stripping) all the characters from the left and right that are passed as string argument. If no arguments are passed, it removes the leading and trailing whitespaces.

Syntax of strip() method

string.strip() - Returns a new string

Example

Code/Output

x = "  Pylenin loves Python   "
print(x.strip()) 
>>> Pylenin loves Python 

x = "*Pylenin loves Python*"
print(x.strip('*')) 
>>> Pylenin loves Python 

x = "*@Pylenin loves Python@*"
print(x.strip('*@')) 
>>> Pylenin loves Python

Check out other commonly used Python string methods.


swapcase()

The swapcase() method in Python returns a string by converting all the upper case letters to lower case and vice versa. Numbers, symbols and whitespaces are ignored.

Syntax of swapcase() method

string.swapcase() - Returns a new string

Example

Code/Output

x = "Pylenin loves Python"
print(x.swapcase()) 
>>> pYLENIN LOVES pYTHON 

x = "Pylenin\nloves\nPython"
print(x.swapcase()) 
>>> pYLENIN    LOVES    pYTHON

Check out other commonly used Python string methods.


title()

The title() method in Python returns a string where the first character of every word is uppercase.

If the word contains a number or a symbol, the first letter after the symbol/number will be converted to uppercase.

Syntax of title() method

string.title() - Returns a new string

Example

Code/Output

x = "pylenin loves python"
print(x.title()) 
>>> Pylenin Loves Python 

x = "My Instagram handle is - @pylenin"
print(x.title()) 
>>> My Instagram Handle Is - @Pylenin 

x = "Check alphanumeric values - 123abc"
print(x.title()) 
>>> Check Alphanumeric Values - 123Abc

Check out other commonly used Python string methods.


translate()

The string translate() method in Python returns a string where each character is mapped to its corresponding character in the translation table.

The translation table is created by using the maketrans() method.

Syntax of translate() method

string.translate(table) 

table: a translation table containing the mapping between characters.

Example 1

Code

str1 = "Pylenin" 
table = str1.maketrans("n", "m") 
print(str1.translate(table))

Output

Pylemim

As you can see, all instances of n were replaced with m.

Example 2 - Mapping table with a dictionary

Code

mapping_dict = {"n":"m"} 
str1 = "Pylenin" 
table = str1.maketrans(mapping_dict) 
print(str1.translate(table))

Output

Pylemim

Example 3 - Removing characters

Code

str1 = "Pylenin?" 
table = str1.maketrans("","","?") 
print(str1.translate(table))

Output

Pylenin

Since the 3rd argument is used to pass in the characters to be removed, the first 2 arguments are being left empty above.

We can achieve the same result by passing in a dictionary.

Code

mapping_dict= {"?":None} 
str1 = "Pylenin?" 
table = str1.maketrans(mapping_dict) 
print(str1.translate(table))

Output

Pylenin

Just use None as values for characters you want removed from your string.

Check out other commonly used Python string methods.


upper()

The upper() method in Python returns a string with all characters converted to uppercase.

Symbols and numbers are ignored.

Syntax of upper() method

string.upper() - Returns a new string

Example

Code/Output

x = "Pylenin loves Python"
print(x.upper()) 
>>> PYLENIN LOVES PYTHON 

x = "Pylenin1992@gmail.com"
print(x.upper()) 
>>> PYLENIN1992@GMAIL.COM

Check out other commonly used Python string methods.


zfill()

The zfill() method in Python concatenates zeros (0) at the beginning of the string, until it reaches the specified length.

If the value of the len parameter is less than the length of the original string, no filling is done.

Syntax of zfill() method

string.zfill(len) 

len: The length of the new string after filling(Required)

Example 1

Code

a = "Pylenin"
b = "Pylenin loves Python"
c = "@pylenin" 

print(a.zfill(10)) 
print(b.zfill(10)) 
print(c.zfill(10))

Output

000Pylenin 
Pylenin loves Python 
00@pylenin

Example 2 - Working with sign prefix (+ and -)

If your strings are prefixed with signs like + and -, then the filling happens after the sign.

Code

a = "+Pylenin"
b = "-Pylenin" 
print(a.zfill(10)) 
print(b.zfill(10))

Output

+00Pylenin 
-00Pylenin

Check out other commonly used Python string methods.


To learn more about Python strings, check out this article.

Python Strings - The Definitive Guide
Learn to handle strings in Python.

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe