بسم الله الرحمن الرحيم

Convert multiline string to a single line in Python

تاريخ النشر : Oct. 26, 2022

None


#

To convert a multiline string to a single line:

  1. Use the str.splitlines() method to get a list of the lines in the string.
  2. Use the str.strip() method to remove leading and trailing whitespace from each line.
  3. Use the join() method to join the list with a space separator.
my_str = """\
First line
Second line
Third line
"""

result = " ".join(line.strip() for line in my_str.splitlines())

print(repr(result))  # 👉️ "First line Second line Third line"

المصدر

https://bobbyhadz.com/blog/python-convert-multiline-string-to-single-line

العودة إلي لغة البرمجة البايثون Python