pythonstringlistmethodsjust

How to process a column (class - string) using the method rjust in Python?


The main problem is, I can't process the column using the specified method rjust(), while I can perfectly apply it in ordinary strings

Sample Input:

8 11 123

Sample Output (what I expect):

008
011
123

I have tried so far:

Str = '8 11 123'
Str_split = Str.split(' ')
#print (Str_split)
Strjoin = '\n'.join(Str_split)
print (Strjoin.rjust(3, '0'))
#8
11
123

And yes, I know it's possible to carry out with help of loop for:

Str = '8 11 123'
Str_split = Str.split(' ') 
print (Str_split) #['8', '11', '123']
for item in Str_split: 
    print (item.rjust(3, '0'))  

But I need to fullfill task without loop, only with string methods


Solution

  • You can use map() instead of for-loop:

    s = "8 11 123"
    
    s = "\n".join(map("{:>03}".format, s.split()))
    print(s)
    

    Prints:

    008
    011
    123
    

    Or:

    s = "\n".join(map(lambda x: x.rjust(3, "0"), s.split()))