>>> print(
... """Dear Alice,
...
... Eve's cat has been arrested for catnapping,
... cat burglary, and extortion.
...
... Sincerely,
... Bob"""
... )
# Dear Alice,
# Eve's cat has been arrested for catnapping,
# cat burglary, and extortion.
# Sincerely,
# Bob
H e l l o w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11
>>> spam = 'Hello world!'
>>> spam[0]
# 'H'
>>> spam[4]
# 'o'
>>> spam[-1]
# '!'
>>> 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'
>>> fizz = spam[0:5]
>>> fizz
# 'Hello'
in
and not in
operators>>> 'Hello' in 'Hello World'
# True
>>> 'Hello' in 'Hello'
# True
>>> 'HELLO' in 'Hello World'
# False
>>> '' in 'spam'
# True
>>> 'cats' not in 'cats and dogs'
# False
An escape character is created by typing a backslash \
followed by the character you want to insert.
Escape character | Prints as |
---|---|
\' |
Single quote |
\" |
Double quote |
\t |
Tab |
\n |
Newline (line break) |
\\ |
Backslash |
>>> print("Hello there!\nHow are you?\nI\'m doing fine.")
# Hello there!
# How are you?
# I'm doing fine.
A raw string entirely ignores all escape characters and prints any backslash that appears in the string.
>>> print(r"Hello there!\nHow are you?\nI\'m doing fine.")
# Hello there!\nHow are you?\nI\'m doing fine.
%
operator>>> name = 'Pete'
>>> 'Hello %s' % name
# "Hello Pete"
We can use the %d
format specifier to convert an int value to a string:
>>> num = 5
>>> 'I have %d apples' % num
# "I have 5 apples"
If your are using Python 3.6+, string f-Strings
are the recommended way to format strings.
>>> name = 'Elizabeth'
>>> f'Hello {name}!'
# 'Hello Elizabeth!'
It is even possible to do inline arithmetic with it:
>>> a = 5
>>> b = 10
>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'
# 'Five plus ten is 15 and not 30.'
>>> name = 'Robert'
>>> messages = 12
>>> (
... f'Hi, {name}. '
... f'You have {messages} unread messages'
... )
# 'Hi, Robert. You have 12 unread messages'
Rounding
>>> a = 3.1415926
>>> f"{a:.2f}"
# '3.14'
Showing as Percentage
>>> a = 0.816562
>>> f"{a:.2%}"
# '81.66%'
Number | Format | Output | description |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | Format float 2 decimal places |
3.1415926 | {:+.2f} | +3.14 | Format float 2 decimal places with sign |
-1 | {:+.2f} | -1.00 | Format float 2 decimal places with sign |
2.71828 | {:.0f} | 3 | Format float with no decimal places |
4 | {:0>2d} | 04 | Pad number with zeros (left padding, width 2) |
11 | {:11d} | 11 | Right-aligned (default, width 10) |
11 | {:<11d} | 11 | Left-aligned (width 10) |
11 | {:^11d} | 11 | Center aligned (width 10) |
upper()
, lower()
and title()
Transforms a string to upper, lower and title case:
>>> greet = 'Hello world!'
>>> greet.upper()
# 'HELLO WORLD!'
>>> greet.lower()
# 'hello world!'
>>> greet.title()
# 'Hello World!'
isupper()
and islower()
methodsReturns True
or False
after evaluating if a string is in upper or lower case:
>>> spam = 'Hello world!'
>>> spam.islower()
# False
>>> spam.isupper()
# False
>>> 'HELLO'.isupper()
# True
>>> 'abc12345'.islower()
# True
>>> '12345'.islower()
# False
>>> '12345'.isupper()
# False
isX()
string methodsMethod | Description |
---|---|
isalpha() |
returns True if the string consists only of letters. |
isalnum() |
returns True if the string consists only of letters and numbers. |
isdecimal() |
returns True if the string consists only of numbers. |
isspace() |
returns True if the string consists only of spaces, tabs, and new-lines. |
istitle() |
returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase characters. |
startswith()
and endswith()
>>> 'Hello world!'.startswith('Hello')
# True
>>> 'Hello world!'.endswith('world!')
# True
>>> 'abc123'.startswith('abcdef')
# False
>>> 'abc123'.endswith('12')
# False
>>> 'Hello world!'.startswith('Hello world!')
# True
>>> 'Hello world!'.endswith('Hello world!')
# True
replace()
The replace()
function is like a “search and replace” operation in a word processor
>>> greet = 'Hello Bob'
>>> nstr = greet.replace('Bob','Jane')
>>> print(nstr)
# Hello Jane
join()
and split()
join()
The join()
method takes all the items in an iterable, like a list, dictionary, tuple or set, and joins them into a string. You can also specify a separator.
>>> ''.join(['My', 'name', 'is', 'Simon'])
'MynameisSimon'
>>> ', '.join(['cats', 'rats', 'bats'])
# 'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
# 'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
# 'MyABCnameABCisABCSimon'
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:
>>> 'My name is Simon'.split()
# ['My', 'name', 'is', 'Simon']
>>> 'MyABCnameABCisABCSimon'.split('ABC')
# ['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
# ['My na', 'e is Si', 'on']
>>> ' My name is Simon'.split()
# ['My', 'name', 'is', 'Simon']
>>> ' My name is Simon'.split(' ')
# ['', 'My', '', 'name', 'is', '', 'Simon']
strip()
, rstrip()
, and lstrip()
>>> spam = ' Hello World '
>>> spam.strip()
# 'Hello World'
>>> spam.lstrip()
# 'Hello World '
>>> spam.rstrip()
# ' Hello World'