Home > Back-end >  Getting rid of white space between name, number and height
Getting rid of white space between name, number and height

Time:11-06

I have txt file like this;

name lastname     17      189cm

How do I get it to be like this?

name lastname, 17, 189cm

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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]

CodePudding user response:

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'
  • Related