Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A few questions about string formating in python. Alignment

FIRST QUESTION

For example, if i want to print a lot of lines with the same width, i could use

print(f'{"INFO":=^50}')
print(f'{"some info":<50}')
print(f'{"another info":>50}')

And will get

=======================INFO=======================
some info                                         
                                      another info

But, what if I want to get something like this?

=======================INFO=======================
some info.............................another info   

Ok. I can do it

print(f'{"INFO":=^50}')
print('some info' + f'{"another info":.>{50-len("some info")}}')

Maybe python has another, the easiest way to do it?

SECOND QUESTION

For align we can use >, <, ^, and = And = works only with numbers. And it works the same as >

For example

print(f'{13:.=5}')
print(f'{13:.>5}')
...13
...13

So Why do we need =, if it works the same? To be sure that the value is a number? What are the pluses it gives more?

like image 265
Sandzhaj Avatar asked Mar 06 '26 01:03

Sandzhaj


2 Answers

For your second question, the answer is in Format Specification Mini-Language:

'='

Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width.

This becomes clear when you have a signed number:

print(f'{-13:0=5}')
# -0013

print(f'{-13:0>5}')
# 00-13
like image 196
Thierry Lathuille Avatar answered Mar 08 '26 21:03

Thierry Lathuille


What you are trying to do is an alignment inbetween two variables. That's quite specific. What then about alignment between three variables, four etc... ?

You can however approach it as an alignment problem for each of the two variables: split the 50 in two parts.

print(f'{"INFO":=^50}')
print(f'{"some info":.<25}{"another info":.>25}')

=======================INFO=======================
some info.............................another info
like image 21
Mace Avatar answered Mar 08 '26 21:03

Mace



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!