Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
rjust part of a string
#1
I am trying to use the rjust method to align part of a string in the following text:

for key in breakfast:
print('%s \t %d calories'%(key,breakfast[key]))


I want to rjust the %d calories part of the string. Not the entire string. Is there a way to do this?
Reply
#2
You should look into the format method of strings, or the even newer f-string syntax (Python 3.6+). The % formatting is really old school. With the newer methods, you can specify justification, width, and fill for each item you insert into the string.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Use Code tag.
Do not use the old string formatting(s% %d) anymore.
breakfast = {'Apple': 50, 'Bread': 150}
for key,value in breakfast.items():
    print(f'{key:<8} {value} calories')
Output:
Apple 50 calories Bread 150 calories
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  ElementTree get attribute value part of string paulo79 1 2,047 Apr-05-2022, 09:13 PM
Last Post: deanhystad
  How to get values from part of a string? mahi926 1 1,838 May-16-2019, 07:27 AM
Last Post: buran

Forum Jump:

User Panel Messages

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