0

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)
Mark
  • 6,052
  • 8
  • 61
  • 129
  • https://www.w3schools.com/python/ref_string_splitlines.asp does the same thing as `replace()` – Andrew Ryan Dec 08 '22 at 21:39
  • 1
    `s = s.replace("\n", "")` doesn't work? – Andrej Kesely Dec 08 '22 at 21:46
  • You could also define the string with single quotes and use the \ operator to show the line flows over to the next. – Lexpj Dec 08 '22 at 21:47
  • `str.splitlines()` does not do the same thing as `str.replace()`. It splits a string on linebreaks into a list of strings, while `str.replace()` replaces occurrences of a character with another character resulting in a single string. – Michael Ruth Dec 08 '22 at 21:49

2 Answers2

1

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) 
Moosa
  • 31
  • 3
0

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.

Michael Ruth
  • 2,938
  • 1
  • 20
  • 27
  • 1
    `str.maketrans` exists to optimize the creation of such dictionaries; `str.maketrans('', '', '\n')` would do the job (you typically do it once as a global and reuse it when you need to). Doesn't make a huge difference for such a small `dict` (but then, for a single character, you should just be using `str.replace`), but it simplifies things a lot for larger numbers of characters to translate. – ShadowRanger Dec 08 '22 at 21:59
  • Interesting analysis of `translate()` and `replace()`: https://stackoverflow.com/a/31145842/4583620 – Michael Ruth Dec 08 '22 at 22:01
  • @ShadowRanger thanks for mentioning `maketrans()`. You're absolutely correct on all points. – Michael Ruth Dec 08 '22 at 22:02
  • 1
    That analysis is rather flawed (being initially based on the ancient `string` module functions initially, not the `str` methods) and wildly out-of-date (Python 3's `str.translate` is almost unrelated to Python 2's version). Sadly, `str.translate` suffers a pretty severe performance degradation in the 2 to 3 transition (handling arbitrary Unicode via a `dict` being a much more expensive prospect than handling just 256 possible byte values in a fixed length C `char` array). They added an optimization that makes `str.translate` not quite so bad for pure ASCII, but it's still slower than it was. – ShadowRanger Dec 08 '22 at 22:09
  • 1
    Amusingly, `str.translate` in Python 3 runs much faster (when you're not deleting any characters, just doing 1-1 translation) if you make the translation table with `bytes.maketrans`, or for the "also deletion" case (when you know the input is bounded to a low ordinal value) by making a mostly dense `tuple` of mappings for the mapping (because looking up integers in a `tuple` is faster than in a `dict`). – ShadowRanger Dec 08 '22 at 22:12
  • @ShadowRanger, yes the analysis is certainly old. I think the value it provides is that it shows a process for performing the analysis. I see a lot of questions of the form "method a vs method b" and "what's the most efficient..." on SO, and they're frequently approached with very poor timing experiments using `time.time()`. I figured this question would eventually go there since `str.replace()` really is the most appropriate way to accomplish the task in this case. – Michael Ruth Dec 08 '22 at 22:45