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.
Table of Contents
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:
Get Your Free Linux training!
Join our free Linux training and discover the power of open-source technology. Enhance your skills and boost your career! Learn Linux for Free!>>> 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 Name | Method Description |
capitalize | Converts the first character of a string to upper case |
casefold | Converts a string to a lowercase string. Supports more conversions than the lower method. Use when localizing or globalizing strings. |
center | Returns a centered string |
count | Returns how many times a character or substring occurs in a string |
encode | Returns an encoded version of a string |
endswith | Checks if a string ends with the specific character or substring |
expandtabs | Specifies a tab size for a string and returns it |
find | Searches for a specific character or substring. Returns the position of where it was first encountered. |
format | The old-school way to add variables inside of a string. Formats a string by embedding values into it and returning the result |
format_map | Formats specific values in a string |
index | Searches for a character or substring in a string. Returns the index at which it was first encountered. |
isalnum | Checks if all the characters of the string are alphanumeric |
isalpha | Checks if all the characters of the string are found in the alphabetical |
isascii | Checks if all the characters of the string are ASCII values |
isdecimal | Checks if all the characters of the string are decimal numbers |
isdigit | Checks if all the characters of the string are numeric digits |
isidentifier | Checks if a string is an identifier |
islower | Checks if all characters of a string are lower case |
isnumeric | Checks if all characters of a string are numeric |
isprintable | Checks if all characters of a string are printable |
isspace | Checks if all characters of a string are white spaces |
istitle | Checks if a string follows title capitalization rules (every word begins with a capital letter) |
isupper | Checks if all characters of a string are upper case |
join | Joins items of an iterable (such as a list) to the end of a string |
ljust | Returns a left-justified version of a string |
lower | Convert a string to lowercase |
lstrip | Returns a left trim version of a string |
maketrans | Returns a translation table of a string for translations |
partition | Breaks a string to parts of three. The desired center part is specified as an argument |
removeprefix | Removes a prefix from the beginning of a string and returns the string without it. |
removesuffix | Removes a suffix from the end of a string and returns the string without it. |
replace | Returns a string where a specific character or substring is replaced with something else |
rfind | Searches a string for a specific character or substring. Returns the last index at which it was found |
rindex | Searches a string for a specific character or substring. Returns the last index at which it was found. |
rjust | Returns a right-justified version of a string |
rpartition | Breaks a string to parts of three. The desired center part is specified as an argument |
rsplit | Splits the string at a specific separator, and returns the parts as a list |
rstrip | Creates and returns a right trim version of a string |
split | Splits the string at the specified separator, and returns the parts as a list |
splitlines | Splits a string at line breaks and returns the lines as a list |
startswith | Checks if a string starts with the specified character or a substring |
strip | Returns a trimmed version of a string |
swapcase | Swaps cases. All uppercase characters become lowercases and vice versa |
title | Converts each word of a string to start with an uppercase letter |
translate | Returns a translated string |
upper | Converts a string to upper case |
zfill | Prefills a string with 0 values |