简体   繁体   中英

% Tuple in an array? python (not append tuple into array)

Say you have something like below:

x=10
l=11
list = ["%s bla","%s bla"%(x,l)]
print(list)

In this situation, you get this error:

TypeError: not all arguments converted during string formatting

I'm assuming this is due to tuples being in an array. Using .format , you'll get:

['{} bla', '11 bla']

Any solutions to my problem?

You need to give each string its own variables:

x=10
l=11
list = ["%s bla" % x,"%s bla" % l]
print(list)

Use zip and a list comprehension to combine the values.

>>> x = 10
>>> L = 11
>>> lst = ["%s bla","%s bla"]
>>> [s % n for s, n in zip(lst, (x, L))]
['10 bla', '11 bla']

In your example, you were applying the formatting only to the second string, which has only one format specifier, but you were passing it two values, hence the error.

If you want to use str.format , just do it like this.

>>> lst2 = ["{} bla","{} bla"]
>>> [s.format(n) for s, n in zip(lst2, (x, L))]
['10 bla', '11 bla']

In latest version of python(3.6 or later), You can also do:

x=10
l=11
l2 = [f"{x} bla",f"{l} bla"]
print(l2)

Output:

['10 bla', '11 bla']

It's because your only assigning it to the last element another option is:

>>> x=10
>>> y=11
>>> l = ["%s bla","%s bla"]
>>> list(map(lambda x: x[0]%x[1],zip(l,[x,y])))
['10 bla', '11 bla']

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