Python Strings Reference

Quick reference to the string functions and methods of Python.

Escape characters
Character Hexadecimal Does what
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\nnn Octal notation where n is in the range 0-7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
\xnn Hexadecimal notation where n is in the range 0-9, a-f (or A-F)
Methods
Method Does what
capitalize() Capitalizes first letter of string
center(width, fillchar) Returns a space-padded string with the original string centered to a total of width columns.
count(str, beg= 0, end=len(string)) Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.
decode(encoding='UTF-8', errors='strict') Decodes the string using the codec registered for encoding. Encoding defaults to the default string encoding.
encode(encoding='UTF-8', errors='strict') Returns encoded string version of string. On error, default is to raise a ValueError unless errors are set to 'ignore' or 'replace'.
endswith(suffix, beg=0, end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.
expandtabs(tabsize=8) Expands tabs in string to multiple spaces. Defaults to 8 spaces per tab if tabsize not provided.
find(str, beg=0, end=len(string)) Determines if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found.
isalnum() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
isdecimal() Returns true if a unicode string contains only decimal characters and false otherwise.
isdigit() Returns true if string contains only digits and false otherwise.
islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
isnumeric() Returns true if a unicode string contains only numeric characters and false otherwise.
isspace() Returns true if string contains only whitespace characters and false otherwise.
istitle() Returns true if string is properly "titlecased" and false otherwise.
isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
join(seq) Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.
len(string) Returns the length of the string
ljust(width [, fillchar]) Returns a space-padded string with the original string left-justified to a total of width columns.
lower() Converts all uppercase letters in string to lowercase.
lstrip() Removes all leading whitespace in string.
maketrans() Returns a translation table to be used in a translate function.
max(str) Returns the max alphabetical character from the string str.
min(str) Returns the min alphabetical character from the string str.
replace(old, new [, max]) Replaces all occurrences of old in string with new or at most max occurrences if max given.
rfind(str, beg=0, end=len(string)) Same as find(), but search backwards in string.
rindex(str, beg=0, end=len(string)) Same as index(), but search backwards in string.
rjust(width [, fillchar]) Returns a space-padded string with the original string right-justified to a total of width columns.
rstrip() Removes all trailing whitespace of string.
split(str="", num=string.count(str)) Splits string according to delimiter str (space if not provided) and returns list of substrings. Splits into at most num substrings if given.
splitlines(num=string.count('\n')) Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
startswith(str, beg=0, end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str. Returns true if so and false otherwise.
strip([chars]) Performs both lstrip() and rstrip() on string.
swapcase() Inverts case for all letters in string.
title() Returns "titlecased" version of string (all words begin with uppercase and the rest are lowercase).
translate(table, deletechars="") Translates string according to translation table str(256 chars), removing those in the del string.
upper() Converts lowercase letters in string to uppercase.
zfill(width) Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).
Operators
Operator Does what
+ Concatenation - Adds values on either side of the operator
* Repetition - Creates new strings, concatenating multiple copies of the same string
[] Slice - Returns the character from the given index
[ : ] Range Slice - Returns the characters from the given range
in Membership - Returns true if a character exists in the given string
not in Membership - Returns true if a character does not exist in the given string
r/R Raw String - Suppresses escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator (the letter "r" or "R") which precedes the quotation marks. The "r" must be placed immediately preceding the first quote mark.
% Format - Performs string formatting
Substitution
Operator Does what
Usage: # print( "I am called %s. I'm %d years old." % ('John Doe', 42) )
%c Single character (or integer).
%s Converts string via str() prior to formatting.
%i Signed decimal integer.
%d Signed decimal integer.
%u Signed decimal integer. Obsolete type (v3.x) – it is identical to 'd'.
%o Signed octal integer.
%x Hexadecimal integer (lowercase).
%X Hexadecimal integer (UPPERcase).
%e Exponential notation (lowercase 'e').
%E Exponential notation (UPPERcase 'E').
%f Floating point real number.
%g Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (The shorter of %f and %e.)
%G Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. (The shorter of %f and %E.)
* Argument specifies width or precision.
- Left justification.
+ Displays the sign character.
<sp> Leaves a blank space before a positive number.
# Adds the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.
0 Pads from left with zeros (instead of spaces).
% '%%' means a single literal '%'.
(var) Mapping variable (dictionary arguments).
m.n. m is the minimum total width and n is the number of digits to display after the decimal point.

More: