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

65 Views Asked by At

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

4

There are 4 best solutions below

1
Andrej Kesely On BEST ANSWER

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()))
0
Barmar On

Call rjust() in the argument to join()

Strjoin = '\n'.join(s.rjust(3, '0') for s in Str_split)
0
Ruslan Nakibov On

I suppose rjust has trouble processing strings with newline '\n' character, although I don't know why. The workaround is to first adjust the strings (I use list comprehension to apply desired function to all elements of str_split) and then print it out joining with \n.

Str = '8 11 123'
Str_split = Str.split(' ')
str_temp = [string.rjust(3,'0') for string in Str_split]
Strjoin = '\n'.join(str_temp)
print(Strjoin)
0
Reilas On

Here is an example, using a list comprehension; a for-loop.

s = '\n'.join([x.rjust(3, '0') for x in input().split()])

And, here is an example, using a regular expression, and a lambda.

import re
s = re.sub(r'\d{1,3}', lambda x: '0' * (3 - len(x.group())) + x.group(), input()).replace(' ', '\n')

Output

8 11 123
008
011
123