python - 句子打印太多次

标签 python string split

def main():
    print('Assignment #4-1, Ayub Hussein, ayub.hussein13@gmail.com')
    for line in fileinput.input():
        words = line.split()
        for i in range(0,len(words)):
            sys.stdout.write(words[i]+', ')
        sys.stdout.write('\n')

main()

输出: 你好,这是\n 你好,这是\n 你好,这是\n

最佳答案

由于您要按空格分割单词并使用逗号重新连接,因此您可以使用 str.join 来获取单个字符串,然后您可以立即写入该字符串,而无需循环。

for line in fileinput.input():
    sys.stdout.write('{}\n'.format(', '.join(line.split())))

或者,

for line in fileinput.input():
    sys.stdout.write(', '.join(line.split()) + '\n')
<小时/>

这是一个小演示 -

In [15]: line = 'hello this is'

In [16]: ', '.join(line.split())
Out[16]: 'hello, this, is'

关于python - 句子打印太多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47895890/

相关文章:

python - 试图合并这个 unicode 字符串列表

java - 字符串中所有数字的动态递增

java - 字符串相乘

javascript - 如何在搜索时仅使用星号通配符?

r - 分层拆分数据

python - 属性错误 : 'TwoCaptcha' object has no attribute 'recaptcha'

python - Django 以不恰当的方式使用 LIKE?

python - 使用 Python SDK 创建 Azure 容器时出现“HTTP header 格式不正确”错误

javascript - 是否仍然没有简单的方法可以将带有复合表情符号的字符串拆分为数组?

c - 试图用两个定界符分开但它不起作用 - C