Strings

Strings

Common String literals and operations



s = "" empty string
s = "spam's" double quotes, same as single
s = 's\np\ta\xOOm' escape sequences
s = """...""" triple quoted blocks strings
s = r'\temp\spam' raw strings
s = b'spam' byte strings python3.x
s = u'spam' unicode strings python2.x
s1 + s2
s * 3
concatenate, repeat
a[i]
s[i:j]
len(s)
index, slice, length
'a %s parrot' % kind string formatted expression
'a {} parrot'.format(kind) string formatted method
s.find('pa') string method calls: search
s.rstrip() remove whitespace
s.replace('pa', 'xx') replacement
s.split(',') split on delimiter
s.isdigit() content test
s.lower() case conversion
s.endswith('spam') end test
'spam'.join(strlist) delimiter join
s.encode('latin-1') unicode encoding
for x in s: print(x)
'spam' in s:
[c * 2 for c in s]
map(ord, s)
iteration, membership


Escape Sequences

\newline ignored(continuation line)
\\ backslash (one)
\' single quote
\" double quote
\a bell
\b backspace
\f formfeed
\n newline (linefeed)
\r carriage return
\t horizontal tab
\v vertical tab
\xhh character with hex value(at most 2 digits)
\ooo character with octal value ooo (up to 3 digits)
\O Null: binary O character(doesnt end string)
\N{ id } unicode database Null
\uhhhh unicode 16 bit hex
\Uhhhhhhhh unicode 32 bit hex
\other not an escape (keeps both \ and other)


String Formatting Expressions

s String ( or any object's str(X) string
r s, but users repr, not str
c character
d decimal (integer)
i integer
u Same as d (obsolete)
o Octal integer
x Hex integer
X X, though prints uppercase
e floating point exponent
E Same as e, but prints uppercase
f Floating point decimal
F Floating point decimal
g Floating point e or f
G Floating point E or F
% literal %