10 Python 3 String Methods and Examples with Cheat Sheet

Python string is a built-in type sequence. Strings can be used to handle textual data in Python. Python Strings are immutable sequences of Unicode points.

There are several built-in Python string methods that allow us to easily make modifications to strings in Python. In this tutorial we will cover the .upper(), .lower(), .count(), .find(), .replace() and str() methods etc.

Python 3 String Methods

  • index() – Searches the string for a specified value and returns the position of where the value is. If the value is a word in a string of sentence, the index will be the number of the first character of the word.
  • istitle() – Returns True if the string follows the rules of a title, which means all words start with an uppercase letter and the rest are lowercase letters.
  • replace() – Replaces the specified value in the string with another specified value in the new string.
  • rfind() – Searches the string for a specified value and returns the last position of where it was found. The index will be the number of the first character of the specified value.
  • rsplit() Splits a string into a list, starting from the right. If no “max” is specified, this method will return the same as the split() method.
  • split() – Splits a string into a list. The default separator is any whitespace, but the separator can be specified (i.e. ,).
  • splitlines() – Uses \n to split the string into a list.
  • strip() – Removes any leading and trailing characters of the specified variables. Unless otherwise specified, the default trailing characters are whitespaces.
  • swapcase() – Swaps all the characters in a string. If the character is an uppercase letter, it’ll turn into a lowercase letter, and vice versa.
  • title() – Converts the first character of each word to uppercase.
  • count() – Returns how many times a character or substring occurs in a string
  • find() – Searches for a specific character or substring. Returns the position of where it was first encountered.

 

Let’s use these test variables:

>>> s = “OH, my paws and whiskers!”
>>> t = “I’m late!”
In the following examples, the Python shell prints the result of the method call, but the original variables s and t are not changed.

Python 3 String Methods – Change Case

>>> s.capitalize()
‘Oh, my paws and whiskers!’
>>> s.lower()
‘oh, my paws and whiskers!’
>>> s.swapcase()
‘oh, MY PAWS AND WHISKERS!’
>>> s.title()
‘Oh, My Paws And Whiskers!’
>>> s.upper()
‘OH, MY PAWS AND WHISKERS!’
Search
>>> s.count(‘w’)
2
>>> s.find(‘w’)
9
>>> s.index(‘w’)
9
>>> s.rfind(‘w’)
16
>>> s.rindex(‘w’)
16
>>> s.startswith(‘OH’)
True

Python 3 String Methods – Modify

>>> ”.join(s)
‘OH, my paws and whiskers!’
>>> ‘ ‘.join(s)
‘O H , m y p a w s a n d w h i s k e r s !’
>>> ‘ ‘.join((s, t))
“OH, my paws and whiskers! I’m late!”
>>> s.lstrip(‘HO’)
‘, my paws and whiskers!’
>>> s.replace(‘H’, ‘MG’)
‘OMG, my paws and whiskers!’
>>> s.rsplit()
[‘OH,’, ‘my’, ‘paws’, ‘and’, ‘whiskers!’]
>>> s.rsplit(‘ ‘, 1)
[‘OH, my paws and’, ‘whiskers!’]
>>> s.split(‘ ‘, 1)
[‘OH,’, ‘my paws and whiskers!’]
>>> s.split(‘ ‘)
[‘OH,’, ‘my’, ‘paws’, ‘and’, ‘whiskers!’]
>>> s.splitlines()
[‘OH, my paws and whiskers!’]
>>> s.strip()
‘OH, my paws and whiskers!’
>>> s.strip(‘s!’)
‘OH, my paws and whisker’

Python 3 String Methods – Format

>>> s.center(30)
‘ OH, my paws and whiskers! ‘
>>> s.expandtabs()
‘OH, my paws and whiskers!’
>>> s.ljust(30)
‘OH, my paws and whiskers! ‘
>>> s.rjust(30)
‘ OH, my paws and whiskers!’
String Type
>>> s.isalnum()
False
>>> s.isalpha()
False
>>> s.isprintable()
True
>>> s.istitle()
False
>>> s.isupper()
False
>>> s.isdecimal()
False
>>> s.isnumeric()
False

Python 3 String Methods

Method NameMethod Description
capitalizeConverts the first character of a string to upper case
casefoldConverts a string to a lowercase string. Supports more conversions than the lower method. Use when localizing or globalizing strings.
centerReturns a centered string
countReturns how many times a character or substring occurs in a string
encodeReturns an encoded version of a string
endswithChecks if a string ends with the specific character or substring
expandtabsSpecifies a tab size for a string and returns it
findSearches for a specific character or substring. Returns the position of where it was first encountered.
formatThe old-school way to add variables inside of a string. Formats a string by embedding values into it and returning the result
format_mapFormats specific values in a string
indexSearches for a character or substring in a string. Returns the index at which it was first encountered.
isalnumChecks if all the characters of the string are alphanumeric
isalphaChecks if all the characters of the string are found in the alphabetical
isasciiChecks if all the characters of the string are ASCII values
isdecimalChecks if all the characters of the string are decimal numbers
isdigitChecks if all the characters of the string are numeric digits
isidentifierChecks if a string is an identifier
islowerChecks if all characters of a string are lower case
isnumericChecks if all characters of a string are numeric
isprintableChecks if all characters of a string are printable
isspaceChecks if all characters of a string are white spaces
istitleChecks if a string follows title capitalization rules (every word begins with a capital letter)
isupperChecks if all characters of a string are upper case
joinJoins items of an iterable (such as a list) to the end of a string
ljustReturns a left-justified version of a string
lowerConvert a string to lowercase
lstripReturns a left trim version of a string
maketransReturns a translation table of a string for translations
partitionBreaks a string to parts of three. The desired center part is specified as an argument
removeprefixRemoves a prefix from the beginning of a string and returns the string without it.
removesuffixRemoves a suffix from the end of a string and returns the string without it.
replaceReturns a string where a specific character or substring is replaced with something else
rfindSearches a string for a specific character or substring. Returns the last index at which it was found
rindexSearches a string for a specific character or substring. Returns the last index at which it was found.
rjustReturns a right-justified version of a string
rpartitionBreaks a string to parts of three. The desired center part is specified as an argument
rsplitSplits the string at a specific separator, and returns the parts as a list
rstripCreates and returns a right trim version of a string
splitSplits the string at the specified separator, and returns the parts as a list
splitlinesSplits a string at line breaks and returns the lines as a list
startswithChecks if a string starts with the specified character or a substring
stripReturns a trimmed version of a string
swapcaseSwaps cases. All uppercase characters become lowercases and vice versa
titleConverts each word of a string to start with an uppercase letter
translateReturns a translated string
upperConverts a string to upper case
zfillPrefills a string with 0 values
David Cao
David Cao

David is a Cloud & DevOps Enthusiast. He has years of experience as a Linux engineer. He had working experience in AMD, EMC. He likes Linux, Python, bash, and more. He is a technical blogger and a Software Engineer. He enjoys sharing his learning and contributing to open-source.

Articles: 275