How can multiple lines be combined into one line in Python?
In Python, you can use the replace() method of strings to merge multiple lines into one. The specific steps are as follows:
- Copy multiple lines of text into a string variable.
- Use the replace() method with strings to replace newline characters with spaces, essentially replacing each newline with a space on every line.
- The final result is the string obtained by merging multiple lines into one line.
Here is an example code:
# 多行文本
multi_line = '''This is line 1.
This is line 2.
This is line 3.'''
# 合并成一行
single_line = multi_line.replace('\n', ' ')
# 输出结果
print(single_line)
When running the above code, the output will be:
This is line 1. This is line 2. This is line 3.
This merges multiple lines of text into one line.