Введение в Python
Теория: Форматирование строк
Полный доступ к материалам
Format strings in Python
Avoid use + to format strings
- Use + operator to concatenate only short strings...
- ...because of performance issues
- Multiple + is ugly
- It creates lots of str in memory
Two ways to format a string
- C-style, % operator (old)
- C#-style, .format method (new)
Old-style
- A little bit faster
- Suitable for those who like C/C++
- Uses tuple/dict as parameters
New-style
- A little bit slower
- Uses *args, **kwargs as parameters
- More complex, it's a mini-language
- You can access nested data
- Common in Py3
- Has extra features in Py3
What to use?
- It depends on the context
- It depends on the style guides
Common patterns
s— stringd— digitf— floatb— binaryx— hexadecimalX— HEXADECIMALo— octal%— to quote a%symbol
Old-style examples
%<spec><type> — unnamed
%.2f
%(<name>)<spec><type> — named
%(price).2f
Use dicts to
- use parameters many times
- make your template more readable
New-style examples
{<index>:<spec>} — unnamed
{0:+0.3f}
{<name>:<spec>} — named
{price:+0.3f}
Remember about str/unicode coerce
Summary
- There are two ways to format a string
- The old one is faster and shorter
- The new one has extra features
- Use those what you want
- Practice