Darko
Darko

Reputation: 607

Formatting a string to be a constant length in Python

Lets say I have a few string titles:

title0 = 'USA'
title1 = 'Canada'

And I want to append a list of '#' characters to the front and back of these titles to give them a constant length so they look like:

######## USA ########
####### Canada ######

With 1 space buffering the start and end of the text. Obviously I can't always get a symmetric number of symbols around the word. Is there a way to do this with built in Python string formatting?

Upvotes: 4

Views: 3701

Answers (1)

FastTurtle
FastTurtle

Reputation: 2311

Python's str.format() has a few options that should get you what you want. You can read more about them here. This should give you what you wanted.

title0 = '{:#^{width}}'.format(' USA ', width=19)
title1 = '{:#^{width}}'.format(' Canada ', width=19)

Or using a similar syntax for the new f-strings/formatted string literals:

width = 19
country = 'USA'
title0 = f'{country:#^{width}}'

Upvotes: 11

Related Questions