Python: String Methods

By Xah Lee. Date: . Last updated: .

This page is a list of all Python's string methods.

For basic tutorial on string, see:

Python strings are not mutable. All string methods return a new string.

Search Substring

  1. str.startswith(prefix,start,end) → Return True if string starts with the prefix, else False. prefix can be a tuple, each element is a string. Optional start, end limits the range of positions to check.
  2. str.endswith(suffix, start, end) → similar to “startwith”, but check the end.
  3. str.find(substr,start,end) → Return index of the first occurrence of substr. Return -1 if substr is not found.
  4. str.rfind(substr,start,end) → similar to “find”, but start at right.
  5. str.index(substr,start,end) → similar to “find”, but raise ValueError when the substring is not found.
  6. str.rindex(substr,start,end) → similar to “index” but start from right.
  7. str.count(substr,start,end) → Return the number of non-overlapping occurrences of substring substr.

in the above, the start and end are optional.

Find/Replace

  1. str.replace("old", "new" , count) → replace occurrences of substring. Only first count number of time is done. count is optional.

Trim String

  1. str.strip("chars") → remove any char in chars at the leading/trailing ends of the string. The "chars" is a string specifying the set of characters to be removed, defaults to whitespace.
  2. str.rstrip("chars") → same as “strip”, but only do trailing end.
  3. str.lstrip("chars") → same as “strip”, but only do beginning end.

String/List Conversion

  1. str.join(iterable) → Change a {list, tuple} into a string, by concatenating elements, and use str as separator.
  2. str.split("sep",maxsplit) → Return a list. Split string using "sep" as the delimiter. If maxsplit is given, at most maxsplit splits are done (result list will have at most maxsplit+1 elements). If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ['1', '2', '3']). Splitting an empty string with a specified separator returns ['']. If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns []. For example, ' 1 2 3 '.split() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].
  3. str.rsplit(sep, maxsplit) → same as “split” but begin at right.
  4. str.splitlines(keepends) → Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true. For example, 'ab c\n\nde fg\rkl\r\n'.splitlines() returns ['ab c', '', 'de fg', 'kl'], while the same call with splitlines(True) returns ['ab c\n', '\n', 'de fg\r', 'kl\r\n']. Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line.
  5. str.partition(sep) → Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
  6. str.rpartition(sep) → same as “partition” but begin at right.

Check Character Case, Character Class

  1. str.isalnum() → Return True if all characters are alphanumeric and there is at least one character, else False.
  2. str.isalpha() → ◇
  3. str.isdigit() → ◇
  4. str.isupper() → ◇
  5. str.islower() → ◇
  6. str.isspace() → check whitespace characters.
  7. str.istitle()true if every word start with cap letter.
  8. unicode.isnumeric() → Return True if there are only numeric characters in S, False otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH.
  9. unicode.isdecimal() → Return True if there are only decimal characters in S, False otherwise. Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.
  1. str.translate(table[, deletechars]) → Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. You can use the maketrans() helper function in the string module to create a translation table. For string objects, set the table argument to None for translations that only delete characters:

Letter Case Conversion

  1. str.capitalize() → capitalize the first character
  2. str.upper() → change to uppercase.
  3. str.lower() → change to lowercase.
  4. str.swapcase() → switch uppercase/lowercase.
  5. str.title() → make each word's first letter uppercase.

Formatting Related Methods

  1. str.format(…) → formatting the string. (replace parts with arguments) [see Python: Format String].
  2. str.center(n) → add space to begin and end of string, so it's centered with respect to n chars.
  3. str.center(n,"char") → fill it with character char
  4. str.ljust(width, "fillchar") → Add fillchar to the end of string, so total length is width. fillchar defaults to space. The original string is returned if width is less than or equal to given string length.
  5. str.rjust(width, "fillchar") → same as “ljust” but done pads on the left.
  6. str.zfill(width) → Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than or equal length.
  7. str.expandtabs() → replace tab char by space.
  8. str.expandtabs(tabsize) → ◇
# -*- coding: utf-8 -*-
# python
# example of string ljust
x = """something in water"""
y = x.ljust(30,"-")
print y
# something in water------------

String Character Encoding/Decoding, Unicode

  1. str.decode(coding) → Decode the string using coding.
  2. str.encode(coding) → Encoded the string using coding. For a list of possible encodings, see section Standard Encodings.

For list of encoding, see: 7.8. codecs — Codec registry and base classes — Python v2.7.6 documentation #codec-base-classes

Python String

  1. Quote String
  2. String Operations
  3. String Methods
  4. Format String

If you have a question, put $5 at patreon and message me.

Python by Example

  1. Python Basics
  2. Print Version String
  3. Builtin Help
  4. Quote String
  5. String Operations
  6. String Methods
  7. Format String
  8. True, False
  9. if then else
  10. for, while, Loops
  11. List Basics
  12. Loop Thru List
  13. Map Function to List
  14. List Comprehension
  15. List Methods
  16. Dictionary
  17. Loop Thru Dict
  18. Dict Methods
  19. Function
  20. Class
  21. List Modules
  22. Write a Module
  23. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. Manipulate Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST
  5. Check Page Load Size
  6. Thumbnail Generation

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Complex Numbers

Advanced

  1. Sort
  2. Copy Nested List
  3. Tuple vs List
  4. Sets, Union, Intersection
  5. Closure in Python 2
  6. Decorator
  7. Append String in Loop
  8. Timing f timeit
  9. Keyword Arg Default Value Unstable

Reference