1
import string
s = "Salut\n\tComment ca va ?"
t = str.maketrans("\n"," ")
y = str.maketrans("\t"," ")
#z = str.maketrans("\n\t","  ")
s = s.translate(t).translate(y)

My Out > 'Salut Comment ca va ?' Expected > 'Salut Comment ca va ?' # only one space after the Salut

After maketrans we need to give space, why cant we give a null

Disclaimer I can use replace and regex for this but that is not the case

#with replace
s.replace('\n', '').replace('\t','')
#with regex
regex = re.compile(r'[\n\t]')
regex.sub("", s)
1
  • You don't need to import string here Commented Oct 22, 2019 at 11:52

4 Answers 4

1

You can replace it with a dict that maps to None.

import string
s = "Salut\n\tComment ca va ?"

t =  {"\t":None,
      "\n": " "}
y = str.maketrans(t)
s = s.translate(y)
print(s)

Or if you don't want to use a dict you can do it all in one line (as per str.maketrans) like so: y = str.maketrans("\n"," ","\t") # third argument chars are mapped to None

Sign up to request clarification or add additional context in comments.

Comments

1

Your problem is, that you replace both (\n and \t) with a space.

s.replace('\n', '').replace('\t', ' ')

Comments

1

another minimal and more general option is to

' '.join(s.split())


s = "Salut\n\tComment ca va ?"
' '.join(s.split())
'Salut Comment ca va ?'

Comments

1

You can use replace.

import string
s = "Salut\n\tComment ca va ?"
t = str.maketrans("\n"," ")
y = str.maketrans("\t"," ")
#z = str.maketrans("\n\t","  ")
s = s.translate(t).translate(y)
print('Before:', s)
s=s.replace("  ", " ") #just added this line
print('After:', s)

But if you don't add extra white space during translation, you won't need this.

Before: Salut  Comment ca va ?
After: Salut Comment ca va ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.