One way to look at str.format method is that curly braces are placeholders:
You can insert what you want into these braces. Advantage over string concatenation is that you visually see spaces etc. You can name placholders too or use indexes:
- String method means, that there should be string before
.format
.
- Placeholders are places where you want to insert values into string
You can insert what you want into these braces. Advantage over string concatenation is that you visually see spaces etc. You can name placholders too or use indexes:
>>> first = 'Eric' >>> last = 'Idle' >>> print('Welcome {given_name} {surname} to Python forum'.format(given_name=first, surname=last)) Welcome Eric Idle to Python forum >>> print('Welcome {} {} to Python forum'.format(first, last)) Welcome Eric Idle to Python forum >>> print('Welcome {0} {1} to Python forum'.format(first, last)) Welcome Eric Idle to Python forum >>> print('Welcome {1} {0} to Python forum'.format(first, last)) Welcome Idle Eric to Python forumBut the 'modern' way is of course f-strings which you will (probably) learn as well (requires 3.6 <= Python):
>> print(f'Welcome {first} {last} to Python forum') Welcome Eric Idle to Python forum
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.