Python 当字符串变量的拆分行之间没有间隙时,将它们连接起来

Python 当字符串变量的拆分行之间没有间隙时,将它们连接起来,python,string,Python,String,我有一个多行字符串变量var_text,如下所示: 'I am a high school student I like Physics' 'I am a high school student I like Physics' 我要做的是连接没有间隙的分割线,使变量如下所示: 'I am a high school student I like Physics' 'I am a high school student I like Physics' 我已尝试使用以下代码行 &qu

我有一个多行字符串变量var_text,如下所示:

'I am a
high
school
student

I like
Physics'
'I am a high school student

I like Physics'
我要做的是连接没有间隙的分割线,使变量如下所示:

'I am a
high
school
student

I like
Physics'
'I am a high school student

I like Physics'
我已尝试使用以下代码行

" ".join(var_text.splitlines())
但它连接所有线,而不考虑它们之间的间隙,因此最终结果如下所示:

'I am a high school student    I like Physics'

有什么建议吗?

您可以通过一个简单的for循环来实现,当您在原始字符串中找到一个空行时,您可以在新字符串中创建一个新行:

s = """'I am a
high
school
student

I like
Physics'"""

r = ""
for line in s.splitlines():
    if line == "":
        r += "\n"
    else:
        r += " " + line
r = r[1:] # Remove the first space

您可以通过一个简单的for循环来实现这一点,在原始字符串中找到空行时,您可以在新字符串中创建新行:

s = """'I am a
high
school
student

I like
Physics'"""

r = ""
for line in s.splitlines():
    if line == "":
        r += "\n"
    else:
        r += " " + line
r = r[1:] # Remove the first space
试试这个:

text='我是一个 高的 学校 大学生 我喜欢 物理学 Joint=.jointext.splitlines 已连接\u拆分=已连接。替换,\n 打印分割 这基本上用新行替换了代码中两行之间的双空格。如果要在列表中存储这两个变量,可以使用以下方法:

text='我是一个 高的 学校 大学生 我喜欢 物理学 Joint=.jointext.splitlines joined\u split=joined.split 打印分割 这将返回一个列表,其中每一行都是一个列表。一个列表以后可能会有用我不知道:

试试这个:

text='我是一个 高的 学校 大学生 我喜欢 物理学 Joint=.jointext.splitlines 已连接\u拆分=已连接。替换,\n 打印分割 这基本上用新行替换了代码中两行之间的双空格。如果要在列表中存储这两个变量,可以使用以下方法:

text='我是一个 高的 学校 大学生 我喜欢 物理学 Joint=.jointext.splitlines joined\u split=joined.split 打印分割 这将返回一个列表,其中每一行都是一个列表。一个列表以后可能会有用我不知道:

试试:

out = '\n\n'.join([rec.replace('\n', ' ') for rec in s.split('\n\n')])
输出:

尝试:

输出:


嗨,那个飞行员@达曼的编辑是一个很好的编辑——这里一般不鼓励对话和闲聊的材料,而支持技术写作。啊,我明白了。我就是那个飞行员@达曼的编辑是一个很好的编辑——这里一般不鼓励对话和闲聊的材料,而支持技术写作。啊,我明白了。知道了