You can use str.translate()
to remove the '\n'
s, or any other character. Provide translate()
with a dict mapping Unicode ordinals of the characters you want to replace to the characters you want to replace them with. In your case:
s.translate({ord('\n'): None})
From `help(str.translate):
Help on built-in function translate:
translate(table, /) method of builtins.str instance
Replace each character in the string using the given translation table.
table
Translation table, which must be a mapping of Unicode ordinals to
Unicode ordinals, strings, or None.
The table must implement lookup/indexing via __getitem__, for instance a
dictionary or list. If this operation raises LookupError, the character is
left untouched. Characters mapped to None are deleted.
Update: I'm not suggesting that str.translate()
is the best or most appropriate solution to the problem, just an option. I think str.replace()
is the natural solution here.