Python Forum
week 1 python help - string formatting ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
week 1 python help - string formatting ?
#19
One way to look at str.format method is that curly braces are placeholders:
  • 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 forum
But 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.
Reply


Messages In This Thread
RE: week 1 python help - by Yoriz - Jul-08-2019, 09:41 PM
RE: week 1 python help - by ichabod801 - Jul-08-2019, 09:43 PM
RE: week 1 python help - by raymond2688 - Jul-08-2019, 09:46 PM
RE: week 1 python help - string formatting ? - by perfringo - Jul-09-2019, 01:35 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  String formatting - tax brackets darek88 1 2,080 Aug-28-2020, 09:59 AM
Last Post: Larz60+
  Calculating the number of day of the week RbaPhoenix 3 2,583 Mar-27-2020, 09:23 PM
Last Post: Larz60+
  String formatting issues? lolatyou 2 2,131 Mar-08-2020, 06:53 AM
Last Post: michael1789
  hardest week yet: some guidence please raymond2688 25 11,102 Aug-22-2019, 05:23 PM
Last Post: ichabod801
  Trying to get the week number from a string of numbers fad3r 2 3,286 Apr-15-2018, 06:52 PM
Last Post: ljmetzger

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020