【问题标题】:Python: for loop - print on the same line [duplicate]Python:for循环-在同一行打印[重复]
【发布时间】:2013-11-30 15:44:11
【问题描述】:

我有一个关于在 Python 3 中使用 for 循环在同一行上打印的问题。我搜索了答案,但找不到任何相关信息。

所以,我有这样的事情:

def function(s):
    return s + 't'

item = input('Enter a sentence: ')

while item != '':
    split = item.split()
    for word in split:
        new_item = function(word)
        print(new_item)
    item = input('Enter a sentence: ')

当用户输入“A short sentence”时,函数应该对其进行处理,并且应该打印在同一行。 假设该函数在每个单词的末尾添加 't',所以输出应该是

At shortt sentencet

但是,目前的输出是:

At
shortt
sentencet

如何在同一行轻松打印结果?或者我应该创建一个新字符串吗

new_string = ''
new_string = new_string + new_item

它被迭代,最后我打印new_string?

【问题讨论】:

    标签: python python-3.x string printing


    【解决方案1】:

    最简单的解决方案是在print 语句中使用逗号:

    >>> for i in range(5):
    ...   print i,
    ...
    0 1 2 3 4
    

    请注意,没有尾随换行符; print 在循环后不带参数会添加它。

    【讨论】:

    • 请注意,这只适用于 Python 2,而 OP 似乎正在使用 Python 3
    【解决方案2】:

    由于print 是 Python3 中的一个函数,您可以将代码简化为:

    while item:
        split = item.split()
        print(*map(function, split), sep=' ')
        item = input('Enter a sentence: ')
    

    演示:

    $ python3 so.py
    Enter a sentence: a foo bar
    at foot bart
    

    使用iterpartial 会更好:

    from functools import partial
    f = partial(input, 'Enter a sentence: ')
    
    for item in iter(f, ''):
        split = item.split()
        print(*map(function, split), sep=' ')
    

    演示:

    $ python3 so.py
    Enter a sentence: a foo bar
    at foot bart
    Enter a sentence: a b c
    at bt ct
    Enter a sentence: 
    $
    

    【讨论】:

    • 我一直有这个疑问,我们可以在遇到列表中的任何项目时使用iter 停止吗?
    • @thefourtheye 我不这么认为,因为我们无法在iter 中访问item,但我们可以使用itertools.takewhile
    • @hcwhsa 你的意思是我们可以结合itertakewhile 来做到这一点?
    • 投反对票的人,你能解释一下原因吗?
    • @thefourtheye 不,只是takewhilefor x in takewhile(lambda x: x not in my_list, (x() for x in repeat(f))),其中ff = partial(input, 'Enter a sentence: ')
    【解决方案3】:

    print函数中使用end参数

    print(new_item, end=" ")
    

    还有另一种方法可以做到这一点,使用理解和join

    print (" ".join([function(word) for word in split]))
    

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 2018-10-29
      • 2019-07-29
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多