Python Forum

Full Version: rjust part of a string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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.
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