1

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')]
Pravat
  • 279
  • 2
  • 16
  • 1
    Tuples are immutable, so you will not be able to change the tuple values from 'A' to 'A###'. You will have to make a copy of the Tuple by replacing the value. – Endyd Jan 30 '19 at 15:57

3 Answers3

2

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')]
yatu
  • 80,714
  • 11
  • 64
  • 111
2

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')]
gold_cy
  • 12,080
  • 3
  • 20
  • 42
1
[(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.

W.Zheng
  • 26
  • 2