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

2024-09-27 07:30:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

'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'

有什么建议吗


Tags: 字符串代码textvaramstudent建议like
3条回答

尝试:

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

输出:

'I am a high school student

I like Physics'

试试这个:

text = '''I am a
high
school
student

I like
Physics'''

joined = " ".join(text.splitlines())
joined_split = joined.replace("  ", "\n")
print(joined_split)

这基本上用新行替换了代码中两行之间的双空格。如果要在列表中存储这两个变量,可以使用以下方法:

text = '''I am a
high
school
student

I like
Physics'''

joined = " ".join(text.splitlines())
joined_split = joined.split("  ")
print(joined_split)

这将返回一个列表,其中每一行都是一个列表。一个列表以后可能有用(我不知道:)

您可以通过一个简单的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

相关问题 更多 >

    热门问题