Python string methods cheat sheet

Keith 181 Published: 06/18/2024

Python string methods cheat sheet

Here is a comprehensive list of Python string methods:

str.lower(): Returns the lowercase version of the string.

Example: "Hello".lower() returns "hello".

str.upper(): Returns the uppercase version of the string.

Example: "Hello".upper() returns "HELLO".

str.title(): Returns a title-cased string, where the first letter is uppercase and subsequent letters are lowercase.

Example: "hello world".title() returns "Hello World".

str.swapcase(): Swaps the case of the string, i.e., makes each character lowercase if it was originally uppercase and vice versa.

Example: "HELLO".swapcase() returns "hElLo".

str.strip([chars]): Returns a copy of the string with leading and trailing characters removed (default is whitespace). Can also specify specific characters to remove.

Example: " Hello ".strip()" returns "Hello", and " 123456 ".strip('0123456789')" removes all digits from the string.

str.lstrip([chars]): Returns a copy of the string with leading characters removed (default is whitespace). Can also specify specific characters to remove.

Example: " Hello ".lstrip()" returns "Hello ", and " 123456 ".lstrip('0123456789')" removes all digits from the start of the string.

str.rstrip([chars]): Returns a copy of the string with trailing characters removed (default is whitespace). Can also specify specific characters to remove.

Example: " Hello ".rstrip()" returns " Hello", and " 123456 ".rstrip('0123456789')" removes all digits from the end of the string.

str.replace(old, new): Returns a copy of the string where all occurrences of old are replaced with new.

Example: "Hello World".replace("World", "Python") returns "Hello Python".

str.split([sep]): Splits the string into substrings separated by the specified separator (default is whitespace). Returns a list of substrings.

Example: "Hello,World,Python".split(',') returns [ "Hello", "World", "Python" ], and "123456789".split('') splits each character into its own element in the list.

str.join(iterable): Joins multiple strings together using the string itself as a separator. Returns a single string.

Example: '-'.join(['Hello', 'World']) returns "Hello-World", and ''join(['A', 'B', 'C']) joins all strings without separators.

str.splitlines([keepends]): Splits a multi-line string into a list of lines using n or rn as the separator. Returns a list of strings.

Example: "HellonWorld".splitlines() returns [ "Hello", "World" ], and "HellornWorld".splitlines() also returns [ "Hello", "World" ].

str.partition(sep): Splits the string into three parts using the specified separator. Returns a tuple where the first element is before the separator, the second element is the separator itself, and the third element is after the separator.

Example: "Hello:World".partition(':') returns [ "Hello", ':', "World" ].

str.rpartition(sep): Splits the string into three parts using the specified separator from the right. Returns a tuple where the first element is before the separator, the second element is the separator itself, and the third element is after the separator.

Example: "Hello:World".rpartition(':') returns [ "Hello:", ':', "World" ].

str.split(sep, maxsplit): Splits the string into substrings separated by the specified separator up to a maximum number of splits (default is infinite). Returns a list of substrings.

Example: "Hello,World,Python".split(',', 1) returns [ "Hello", "World,Python" ], and "123456789".split('', 3) splits into four parts.

str.zfill(width): Pads the string with zeros on the left until it reaches a specified width. Returns a copy of the string.

Example: "12".zfill(5) returns "0012".

str.ljust(width), str.rjust(width), and str.center(width): Pad the string with spaces or other characters on the left, right, or center until it reaches a specified width. Returns a copy of the string.

Example: "Hello".ljust(10) returns "Hello ", and "Hello".rjust(10) returns " Hello".

str.decode([encoding]): Converts the string into bytes using the specified encoding (default is UTF-8). Returns bytes.

Example: "Hello".encode('latin1') converts the string to bytes with Latin 1 encoding.

str.encode([encoding]): Converts the string into bytes using the specified encoding (default is UTF-8). Returns bytes.

Example: "Hello".encode(), equivalent to "Hello".encode('utf-8'), converts the string to bytes with UTF-8 encoding.

str.maketrans(t1, t2): Creates a translation table for use with str.translate() or str.trans methods. Returns a dictionary.

Example: maketrans('aeiou', 'AAAAEEOO'), equivalent to { 'a': 'A', 'e': 'E', 'i': 'I', 'o': 'O', 'u': 'U' }, can be used to replace vowels with uppercase equivalents.

str.translate(table): Applies a translation table created by str.maketrans() to the string and returns the resulting string.

Example: translate({ 'a': 'A', 'e': 'E', 'i': 'I', 'o': 'O', 'u': 'U' }) replaces vowels with uppercase equivalents in the original string.

These are just a few examples of what you can do with Python's built-in string methods. The full list is much longer and includes many more methods for manipulating strings, which are essential for most programming tasks!

Python string methods documentation

The wonderful world of Python strings!

Python's str class provides an impressive arsenal of methods to manipulate and transform your strings. Here's a comprehensive guide to get you started:

1. Conversion Methods

These methods allow you to convert your strings between different formats:

.lower(): Converts the entire string to lowercase.

.upper(): Converts the entire string to uppercase. .title(): Converts the first character of each word to uppercase and makes all other characters lowercase. .swapcase(): Swaps the case of the entire string.

2. Formatting Methods

These methods help you format your strings:

.format() (Python 3.x only): Allows you to insert variables into a string template using placeholder values ({}) or named placeholders ({} -> 'name'). f-strings (Python 3.6+): Uses an f prefix followed by double quotes """, and supports variable insertion using {} or -> name. .zfill(n): Pads the string with leading zeros until it reaches a specified width n.

3. Search and Replace Methods

These methods help you find specific patterns in your strings:

.find(pattern): Returns the index of the first occurrence of a pattern (-1 if not found). .rfind(pattern): Returns the index of the last occurrence of a pattern (-1 if not found). .index(pattern): Raises a ValueError if the pattern is not found. .count(pattern): Returns the number of occurrences of a pattern.

4. Manipulation Methods

These methods let you modify your strings in various ways:

.strip(chars): Removes leading and trailing characters from the string (default: whitespace). .lstrip(chars), .rstrip(chars): Similar to strip(), but only removes characters from the beginning or end, respectively. .split(sep), .rsplit(sep): Splits a string into substrings using a separator (or whitespace by default). The order of these methods determines whether you split from left (split) or right (rsplit). .join(sep): Joins multiple strings with a specified separator.

5. Other Methods

These miscellaneous methods might come in handy:

.replace(old, new): Replaces all occurrences of old with new. .encode(), .decode(): Converts the string to/from a bytes object using a specified encoding scheme. .splitlines(): Splits a multi-line string into individual lines (or None if no separator is provided). .partition(sep): Similar to split() but returns a tuple containing the first part, separator, and remaining parts.

Bonus Tip: When working with strings in Python, it's essential to understand that most methods will return a new string instead of modifying the original one. This allows for more efficient and flexible manipulation of your data!