Home > Software engineering >  python: paste lines in a multi-line string
python: paste lines in a multi-line string

Time:12-09

Suppose I have a multi-line string, where lines are separated with \n symbol. What would be my options to merge the lines together in a single lengthy string? I have only the following mind:

s = """Text line
another text line
and another long text line"""

s = s.replace('\n', '')
print(s)

CodePudding user response:

Here are some Options

s = """Text line
another text line
and another long text line"""

#option 1
s1 = s.replace('\n', ' ')

#option 2
s2 = s.split('\n')
s2= " ".join(s2)

#option 3
s3 = s.splitlines()
s3 = " ".join(s3)

#option 4
import re 
s4 = re.sub('\n', ' ', s)
print(s4) 

CodePudding user response:

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.

  • Related