简体   繁体   中英

Using String Formatting in Python

I have a predetermined format

FORMAT = "{0:<30}{1}"

Which I want to use in relation to tuple x, where tuple x is something like

['bananas', '246']

I've tried everything I can, and it keeps spitting out errors. How do I use the format with my tuple?

EDIT: My expected output should (I think) simply put spaces between the first and second items, like

Bananas                                     246

I tried

x = FORMAT(x)

which gives

TypeError: 'str' object is not callable

str.format expects multiple arguments corresponding to the placeholders in the string being formatted, rather than a single argument that contains multiple items to be formatted. Therefore I think what you want is:

FORMAT.format(*['bananas', '246'])

where the * means "unpack the items in the iterable as separate positional arguments", ie effectively calls:

FORMAT.format('bananas', '246')

If your list is eg

x = ['bananas', '246']

then you can convert to a formatted string like:

x = FORMAT.format(*x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM