Strings
Resources
- Python f-strings on RealPython site.
- Using % and .format() for great good!
Make a long number readable
>>> "{:,}".format(12345678910)
12,345,678,910
Representing objects
Printing a string and using repr
.
>>> print('abc')
abc
>>> print(repr('abc'))
'abc'
Printing using .format
and !r
.
>>> print('{}'.format('abc'))
abc
>>> print('{!r}'.format('abc'))
'abc'
Without using print, the value is quoted.
>>> '{}'.format('abc')
'abc'
>>> '{!r}'.format('abc')
"'abc'"
The repr
function gives out which can be used to create a new object. So a string must be quoted.
>>> print(repr('abc'))
'abc'
>>> print(repr(123))
123
>>> print(repr(True))
True
For classes, the __repr__
might be set to exactly match the contents so a new instance be created, or it might be a summary. But it won’t be set by default.
From Python String Conversion 101: Why Every Class Needs a “repr” article.
class Foo:
def __init__(self, color, mileage):
self.color = color
self.mileage = mileage
def __repr__(self):
return (f'{self.__class__.__name__}('
f'{self.color!r}, {self.mileage!r})')
def __str__(self):
return f'a {self.color} foo'
Formatting styles
New style
'{} {}'.format(foo, bar)
'{0} {1}'.format(foo, bar)
'{foo} {bar}'.format(foo=foo, bar=bar)
Use f-strings in Python 3.6+.
f'{foo} {bar}'
Modifiers
Using repr
.
'{0!r}'.format(foo)
Using ASCII
'{0!a}'.format(foo)
Alignment
Align left.
'{:10}'
'{:<10}'
Align right with padding.
'{:>10}'
Align center.
'{:^10}'
Format integer. Aligns right.
'{:4d}'.format(42)
# => ' 42'
Round a float.
# Default to 7.6 values (7 total length and 6 after point).
'{:f}'.format(3.141592653589793)
# => '3.141593'
# Custom
'{:3.2f}'.format(3.141592653589793)
# => '3.14'
# Add padding.
'{:06.2f}'.format(3.141592653589793)
# => '003.14'
Old style
'%s %s' % (foo, bar)
Debugging
logging.debug("User name: %s", name)
Template Strings
A simpler and less powerful mechanism, but it is recommended when handling format strings generated by users. Due to their reduced complexity template strings are a safer choice.
from string import Template
name = 'Elizabeth'
t = Template('Hey $name!')
t.substitute(name=name)
# => 'Hey Elizabeth!'
Resources
Truncate long string
import textwrap
textwrap.shorten("Hello world!", width=12)
# => 'Hello world!'
textwrap.shorten("Hello world!", width=11)
# > 'Hello [...]'
textwrap.shorten("Hello world", width=10, placeholder="...")
# => 'Hello...'
'{:.5}'.format('xylophone')
# => 'xylop'
Working with strings
Repeating strings
>>> '---'*10
'------------------------------'
>>> ['---']*10
['---', '---', '---', '---', '---', '---', '---', '---', '---', '---']
| >>> print(" | ".join(['---']*10)) |
| ----------- | ------------------- || | | | | | | |
Convert strings to markdown table
header = "a,b,c".split(',')
row = "1,2,3".split(",")
print(" | ".join(header))
print(" | ".join(['---']*len(header)))
print(" | ".join(row))
| a | b | c |
| --- | --- | --- |
| 1 | 2 | 3 |
a | b | c |
---|---|---|
1 | 2 | 3 |
Convert strings to dict
header = "a,b,c".split(',')
row = "1,2,3".split(",")
row_dict = {k: v for k, v in zip(header, row)}
print(row_dict)
# {'a': '1', 'b': '2', 'c': '3'}
Hex color code
Convert integer to hex string
>>> hex(12525)
'0x30ed'
Remove prefix
>>> "{:x}".format(12525)
'30ed'
Left-pad with spaces
>>> "{:6x}".format(12525)
' 30ed'
Left-pad with zeroes
"{:06x}".format(12525)
'0030ed'
Use f-strings
>>> color_number = 12525
>>> f"{color_number:06x}"
'0030ed'
Hex to integer
>>> x = 0x30ed
>>> type(x)
<type 'int'>
Max for 6-digit hex code.
>> 0xffffff
16777215
Textwrap
Dedent
Remove common whitespace
text = textwrap.dedent("""\
a
b
c
""")
print(text)
a
b
c