python-3.x - 将列表组合成字符串
问题描述
我正在编写一些代码,这些代码应该在满足某些要求时更改字符串以创建新行。但是,由于我将字符串更改为列表,因此它最终打印为列表,并且我不知道如何将列表转换为字符串或通过将字符串保留为字符串来分析字符串。此外,如果有人能解释为什么添加“\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.
解决方案
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.
推荐阅读
- macos - 如何用 seq 生成七位数的整数范围?
- python - Pytorch CNN 训练中的“RuntimeError: expected scalar type Double but found Float”
- python - 如何压缩非迭代
- image - 在谷歌表格中插入图片数量是否有限制
- flutter - 如何使 Card() 在颤动中领先、标题、尾随固定位置
- angular - 警告:清理不安全的 URL 值数据:text/html;base64,
- python - Pytorch nn.Linear RuntimeError: mat1 dim 1 必须匹配 mat2 dim 0
- laravel - 多对多数据透视表上的自定义范围
- flutter - 断言失败:第 19 行第 16 行:'纬度!= null':不正确。颤振错误
- javascript - 我可以用更新的 Object.fromEntries(new FormData(form)) 替换表单元素循环解析吗?