Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 648
Darko Avatar asked Oct 28 '25 21:10

Darko


1 Answers

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}}'
like image 67
FastTurtle Avatar answered Oct 31 '25 11:10

FastTurtle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!