Manipulating Strings
Manipulating Strings
Share
Escape characters
An escape character is created by typing a backslash \ followed by the character you
want to insert.
\t Tab
\\ Backslash
Escape character Prints as
\b Backspace
\r Carriage Return
Raw strings
A raw string entirely ignores all escape characters and prints any backslash that
appears in the string.
Multiline Strings
>>> print(
... """Dear Alice,
...
... Eve's cat has been arrested for catnapping,
... cat burglary, and extortion.
...
... Sincerely,
... Bob"""
... )
# Dear Alice,
# Sincerely,
# Bob
H e l l o w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11
Indexing
>>> spam = 'Hello world!'
>>> spam[0]
# 'H'
>>> spam[4]
# 'o'
>>> spam[-1]
# '!'
Slicing
>>> spam = 'Hello world!'
>>> spam[0:5]
# 'Hello'
>>> spam[:5]
# 'Hello'
>>> spam[6:]
# 'world!'
>>> spam[6:-1]
# 'world'
>>> spam[:-1]
# 'Hello world'
>>> spam[::-1]
# '!dlrow olleH'
>>> greet.lower()
# 'hello world!'
>>> greet.title()
# 'Hello World!'
>>> spam.isupper()
# False
>>> 'HELLO'.isupper()
# True
>>> 'abc12345'.islower()
# True
>>> '12345'.islower()
# False
>>> '12345'.isupper()
# False
isalnum() returns True if the string consists only of letters and numbers.
isspace() returns True if the string consists only of spaces, tabs, and new-lines.
returns True if the string consists only of words that begin with an
istitle() uppercase letter followed by only lowercase characters.
>>> 'abc123'.endswith('12')
# False
split()
The split() method splits a string into a list. By default, it will use whitespace to
separate the items, but you can also set another character of choice:
>>> 'MyABCnameABCisABCSimon'.split('ABC')
# ['My', 'name', 'is', 'Simon']
>>> 'Hello'.rjust(20)
#' Hello'
>>> 'Hello'.ljust(10)
# 'Hello '
>>> 'Hello'.center(20)
#' Hello '
An optional second argument to rjust() and ljust() will specify a fill character apart
from a space character:
>>> spam.lstrip()
# 'Hello World '
>>> spam.rstrip()
# ' Hello World'
>>> sentence.count('e')
#9
>>> sentence.count('e', 6)
#8
# returns count of e after 'one sh' i.e 6 chars since beginning of string
>>> sentence.count('e', 7)
#7
Replace Method
Replaces all occurences of a given substring with another substring. Can be optionally
provided a third argument to limit the number of replacements. Returns a new string.