简体   繁体   中英

How to fill tuple with special character

I have a tuple like below:

L1 = [(10955, 'A'), (10954, 'AB'), (10953, 'AB'), (10952, 'ABCD')]

I want to fill the tuple values with '#' if the length is less than 4.

I want my output as below:

L1 = [(10955, 'A###'), (10954, 'AB##'), (10953, 'AB##'), (10952, 'ABCD')]

You can use the following list comprehension, where the symbol "#" is added as many times as necessary for the string to have length 4:

[(i,j + '#'*(4-len(j))) for i,j in L1]
[(10955, 'A###'), (10954, 'AB##'), (10953, 'AB##'), (10952, 'ABCD')]

You can use the built-in string method ljust

[(x, y.ljust(4, '#')) for x, y in L1]

[(10955, 'A###'), (10954, 'AB##'), (10953, 'AB##'), (10952, 'ABCD')]
[(x, y.ljust(4, '#')) for x, y in L1]

I think it is similar to How can I fill out a Python string with spaces?

str.ljust(width[, fillchar]) is the key.

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