Raw strings
Raw strings prints any backslash in the string.
"""Raw strings:
A raw string ignores all escape characters"""
print('That\'s my cat')
# That's my cat
print(r'[a-z\'A-Z]')
# [a-z\'A-Z]
Interpolation
You don't have to use str() to convert values to string.
"""String interpolation:
The %s operator inside the string is a marker to be replaced.
"""
name = 'John'
age = 40
message = 'My name is %s and I\'m %s old'
print(message % (name, age))
# My name is John and I'm 40 old
print("I am %s and have %s dogs " % ("John", 2))
# I am John and have 2 dogs
F-String
In a f-string braces are used insteed of %s
"""f-string:
Is similar to string interpolation, except that ...
braces are used insteed of %s
The same result can be obtain using format() method.
"""
name = 'John'
age = 40
message = f'My name is {name} and I\'m {age} old'
print(message)
# My name is John and I'm 40 old
print('My name is {} and I am {} old'.format(name, age))
# My name is John and I am 40 old
print('My name is {0}'.format(name, age))
# My name is John
Strip
Strip off whitespace characters (\s, \t, \n)
"""Removing white spaces:
Use strip(), rstrip() and lstrip() ...
to strip off whitespace characters (\s, \t, \n)
"""
HELLO = ' Hello World '
HELLO_STRIP = HELLO.strip()
HELLO_LSTRIP = HELLO.lstrip()
HELLO_RSTRIP = HELLO.rstrip()
assert f'x{HELLO_STRIP}x' == 'xHello Worldx'
assert f'x{HELLO_LSTRIP}x' == 'xHello World x'
assert f'x{HELLO_RSTRIP}x' == 'x Hello Worldx'
Last update: 92 days ago