misguided
misguided

Reputation: 3789

String Formatting - Python

I have two strings , the length of which can vary based on input. I want to format them aligning them to middle and filling up the rest of the space with ' '. Each string starting adn ending with ^^ .

Case1:

String1 = Longer String
String2 = Short

Output required:

^^   Longer String   ^^
^^       Short       ^^

Case2:

String1 = Equal String1
String2 = Equal String2

Output required:

^^       Equal 1      ^^
^^       Equal 2      ^^

Case3:

String1 =  Short
String2 = Longer String

Output required:

^^       Short       ^^
^^   Longer String   ^^

Across all three outputs the legth has been kept constant , so that uniformity is maintained.

My initial thought is that this will involve checking lengths of the two strings in the following format

if len(String1) > len(String2):
  #Do something
else:
  #Do something else

Upvotes: 1

Views: 121

Answers (3)

misguided
misguided

Reputation: 3789

I ended up using the following code, which worked for me . 19 can be replaced by any number based on how long you want your string to be formatted to .

print "^^",'{:^19}'.format(String1),"^^"
print "^^",'{:^19}'.format(String2),"^^"

Upvotes: 0

dawg
dawg

Reputation: 103694

If you want to reference just setting the centering with respect to two strings:

cases=[
    ('Longer String','Short'),
    ('Equal 1','Equal 2'),
    ('Short','Longer String'),
    ]

for s1,s2 in cases:
    w=len(max([s1,s2],key=len))+6
    print '^^{:^{w}}^^'.format(s1,w=w)
    print '^^{:^{w}}^^'.format(s2,w=w)
    print

Prints:

^^   Longer String   ^^
^^       Short       ^^

^^   Equal 1   ^^
^^   Equal 2   ^^

^^       Short       ^^
^^   Longer String   ^^

Or, if you want to test the width of more strings, you can do this:

cases=[
    ('Longer String','Short'),
    ('Equal 1','Equal 2'),
    ('Short','Longer String'),
]

w=max(len(s) for t in cases for s in t)+6
for s1,s2 in cases:
    print '^^{:^{w}}^^'.format(s1,w=w)
    print '^^{:^{w}}^^'.format(s2,w=w)
    print 

prints:

^^   Longer String   ^^
^^       Short       ^^

^^      Equal 1      ^^
^^      Equal 2      ^^

^^       Short       ^^
^^   Longer String   ^^

Upvotes: 0

phihag
phihag

Reputation: 287735

Simply use str.center:

assert '^^' + 'Longer String'.center(19) + '^^' == '^^   Longer String   ^^'
assert '^^' + 'Short'.center(19) + '^^'         == '^^       Short       ^^'

Upvotes: 2

Related Questions