I am starting out with strings (creditcard numbers and validity status) such as:
'378282246310005 Invalid',
'30569309025904 Invalid',
'6011111111111117 valid'
and I would like to obtain final strings, where the total length is 40:
'378282246310005 Invalid',
'30569309025904 Invalid',
'6011111111111117 valid'
Besides the Python string methods 'rjust', 'ljust' and 'center', are there any built-in string method to accomplish such a task, or would I need to write some function for it for example?
So far, I have tried:
string = '378282246310005 {} Invalid'
while len(string) < 40:
string = string.format(' ')
Not sure how to progress from here.
Here's a manual solution using str.split
and str.join
:
L = ['378282246310005 Invalid',
'30569309025904 Invalid',
'6011111111111117 valid']
def formatter(x):
x_split = x.split()
n = sum(map(len, x_split))
return (' '*(40-n)).join(x_split)
print(*map(formatter, L), sep='\n')
378282246310005 Invalid
30569309025904 Invalid
6011111111111117 valid
This works even if your input string contains multiple whitespace.