python - 使用 "while"时删除最后一个字符

标签 python

我用 Python 编写了一个函数来将我的数据排序为字典语法,但是因为我使用的是 while,所以我想删除一个逗号以避免语法无效。

例如下面的代码:

file = open("test.txt","w", encoding="utf-8")
number = 0
while number < 5:
    file.write("some text" + ", ")
    number += 1

这将创建包含以下文本的 test.txt:

some text, some text, some text, some text, some text,

我想删除最后添加的“,”,看起来像:

some text, some text, some text, some text, some text

有什么想法吗?

最佳答案

我会使用join

text_to_write = 5 * ['the text']
file.write(', '.join(text_to_write))

关于python - 使用 "while"时删除最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54788493/

相关文章:

python - 相当于 aws cdk 中的 !Ref

python - 部分构造函数初始化的性能

python - 如何打印前面有一定数量空格的整数?

python - 在我输入的某些路径中保存文件时出现问题

python - 如何将集合中的元素与多个字典条目关联

python - 如何使用 Python 写入 Excel 电子表格?

python - “Popen”对象不可迭代

python - 使用 asyncio/aiohttp 获取多个 URL 并重试失败

python - 如何在 Jupyter 笔记本中获得交互式 Bokeh

python - 通过Kraken API获取BTC历史数据