python怎么只打印其中一行_Python:for循环 – 在同一行打印[复制]

参见英文答案 > Print new output on same line                                    7个

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

所以,我有这样的事情:

def function(variable):

some code here

return result

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: ')

当用户输入句子“短句”时,该函数应该对它做一些事情并且它应该打印在同一行上.

假设函数将’t’添加到每个单词的末尾,因此输出应为

在短期内判刑

但是,目前的输出是:

肖特

sentencet

如何轻松地在同一行上打印结果?或者我应该制作一个新的字符串

new_string = ''

new_string = new_string + new_item

它是迭代的,最后我打印new_string?

解决方法:

在打印功能中使用end参数

print(new_item, end=" ")

使用理解和加入还有另一种方法可以做到这一点.

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

标签:python,python-3-x,string

来源: https://codeday.me/bug/20190926/1819218.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值