format string Python

Introduction

format strings were available in Python 3.0 and are described in PEP 3101

Syntax

str.format()

Examples

name = "Alex Brezhnev" print("Hello, {}".format(name))

python2 format_ex.py

Hello, Alex Brezhnev

name = "Alex" url = "alexbrezhnev.ru" print("Hello, {n} your site is ready at {u}".format(n=name, u=url))

python2 format_ex.py

Hello, Alex your site is ready at alexbrezhnev.ru

print("My website name is {0[name]}, and address is {0[url]}".format(dict(name="AndreyOlegovich", url="www.aredel.com")))

python2 format_ex.py

My website name is AndreyOlegovich, and address is www.aredel.com

Banner image

Example of generating characters

Let us look at printing Unicode characters using the function unichr()

# Python 2 for i in range(128): print("unichr({counter}): {value}".format(counter=i, value=unichr(i)))

python format_string.py

unichr(0): unichr(1): … unichr(33): ! unichr(34): " unichr(35): # … unichr(64): @ unichr(65): A unichr(66): B unichr(67): C … unichr(97): a … unichr(122): z unichr(123): { unichr(124): | unichr(125): } unichr(126): ~ unichr(127):

Article author: Andrei Olegovich