首页 > 解决方案 > 将列表组合成字符串

问题描述

我正在编写一些代码,这些代码应该在满足某些要求时更改字符串以创建新行。但是,由于我将字符串更改为列表,因此它最终打印为列表,并且我不知道如何将列表转换为字符串或通过将字符串保留为字符串来分析字符串。此外,如果有人能解释为什么添加“\n”实际上不会创建换行符,我也将不胜感激。

我试图str(variable)将列表转换为字符串,但这似乎不起作用。此外,我尝试更改附加方法以查看是否真的会插入换行符;variable.append, +=, 但这些似乎都不起作用。我是 Python 和编程的新手,并且正在苦苦挣扎。

    sentence= "Hello. My name is George... Michael! David Browns."
    def sentence_splitter(target_sentence):
        target_sentence = list(target_sentence)
        for character in range(len(target_sentence)):
            if target_sentence[character:character+2] == list(". ") or target_sentence[character:character+2] == list("! "):
                target_sentence[character:character+2] += list("\n")
        print(str(target_sentence))

sentence_splitter(句子)

当前结果:

['H', 'e', 'l', 'l', 'o', '.', ' ', '\n', 'M', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'G', 'e', 'o', 'r', 'g', 'e', '.', '.', '.', ' ', '\n', 'M', 'i', 'c', 'h', 'a', 'e', 'l', '!', ' ', '\n', 'D', 'a', 'v', 'i', 'd', ' ', 'B', 'r', 'o', 'w', 'n', 's', '.']

预期结果:

Hello.

My name is George...

Michael!

David Browns.

标签: python-3.x

解决方案


sent = ""
for i in sentence.split(" "):
    sent = sent + " " + i
    if i[-1] in ['.', '!']:
        sent = sent + "\n"

print(sent)

输出:

 Hello.
 My name is George...
 Michael!
 David Browns.

推荐阅读