Home > Software design >  Replaces whitespaces with a tab and vice versa with regex in python
Replaces whitespaces with a tab and vice versa with regex in python

Time:06-08

I am trying to replace whitespaces with tab using regex in python

txt = "Nasa has   fixed a   problem"
x = re.sub("\s", "\t", txt)

and I get

'Nasa\thas\t\t\tfixed\ta\t\t\tproblem'

How can i do this in proper manner?

CodePudding user response:

Do you mean this? also to run this code online heres link https://replit.com/@Nava10Y/Replaces-whitespaces

txt = "Nasa has   fixed a   problem"
x = txt.replace(" ", "\s")
print(x)

print("\n\nReversed part:")#ignore this


#reverse 
x = x.replace("\s", " ")
print(x)

output

Nasa\shas\s\s\sfixed\sa\s\s\sproblem


Reversed part:
Nasa has   fixed a   problem
>>>

CodePudding user response:

i used import re heres another link https://replit.com/@Nava10Y/Replaces-whitespaces-v2

import re

txt = "Nasa has   fixed a   problem"

x = re.sub("\s", "\t", txt)
print(x)

output

Nasa    has         fixed   a           problem
>>>
  • Related