-1

I have txt file like this;

name lastname     17      189cm

How do I get it to be like this?

name lastname, 17, 189cm
Barmar
  • 741,623
  • 53
  • 500
  • 612

4 Answers4

1
text = 'name lastname     17      189cm'
out = ', '.join(text.rsplit(maxsplit=2)) # if sep is not provided then any consecutive whitespace is a separator
print(out) # name lastname, 17, 189cm
Алексей Р
  • 7,507
  • 2
  • 7
  • 18
1

You can use regex to replace multiple spaces (or tabs) with a comma:

import re

text = 'name lastname     17      189cm'
re.sub(r'\s\s+|\t', ', ', text)
RJ Adriaansen
  • 9,131
  • 2
  • 12
  • 26
1

Using str.strip and str.split:

>>> my_string = 'name lastname     17      189cm'
>>> s = list(map(str.strip, my_string.split()))
>>> ', '.join([' '.join(s[:2]), *s[2:] ])
'name lastname, 17, 189cm'
Jab
  • 26,853
  • 21
  • 75
  • 114
0

You could use re.sub:

import re
s = "name lastname       17         189cm"
re.sub("[ ]{2,}",", ", s)

PS: for the first problem you proposed, I had the following solution:

s = "name lastname 17 189cm"
s[::-1].replace(" ",",", 2)[::-1]
nikeros
  • 3,302
  • 2
  • 10
  • 26