python:水平打印而不是当前默认打印
我想知道我们是否可以在python中按行打印 基本上我有一个循环,这个循环可能会进行数百万次,我正在打印出这个循环中的一些战略计数。。所以如果我能按行打印,那就太酷了python:水平打印而不是当前默认打印,python,Python,我想知道我们是否可以在python中按行打印 基本上我有一个循环,这个循环可能会进行数百万次,我正在打印出这个循环中的一些战略计数。。所以如果我能按行打印,那就太酷了 print x # currently gives # 3 # 4 #.. and so on 我看起来有点像 print x # 3 4 在Python2中: data = [3, 4] for x in data: print x, # notice the comma at the end of the l
print x
# currently gives
# 3
# 4
#.. and so on
我看起来有点像
print x
# 3 4
在Python2中:
data = [3, 4]
for x in data:
print x, # notice the comma at the end of the line
或者在Python3中:
for x in data:
print(x, end=' ')
印刷品
3 4
您可以在调用打印后添加逗号,以避免换行:
print 3,
print 4,
# produces 3 4
只需在要打印的项目末尾添加一个
,
print x,
# 3 4
如果你在结尾加逗号,它应该适合你
>>> def test():
... print 1,
... print 2,
...
>>> test()
1 2
答复
RangeFinal 19
Prime Numbers in the range
3 5 7 9 11 13 15 17
使用此代码进行打印
打印(x,end=“”)
对于python 2:
for x in num:
print x,
对于python 3:
for x in num:
print(x, end = ' ')
Python 3:
l = [3.14, 'string', ('tuple', 'of', 'items')]
print(', '.join(map(repr, l)))
输出:
我的名单:
mylist = list('abcdefg')
最简单的方法是,在一行中仅打印mylist
中的原始值:
print(*iter(mylist), sep=' ')
# Output:
# a b c d e f g
可自定义的方式,更改全部或少数mylist
值:
# Default values
print(*(x for x in mylist), sep=' ')
# Output:
# a b c d e f g
# Changing all values
print(*(ord(x) for x in mylist), sep=' ') # ord() return a unicode code from a character
# Output:
# 97 98 99 100 101 102 103
# Changing just few values
print(*(x if x != 'c' else '_' for x in mylist), sep=' ')
# Output:
# a b _ d e f g
您可以在循环完成后始终选中
x
并打印:)
mylist = list('abcdefg')
print(*iter(mylist), sep=' ')
# Output:
# a b c d e f g
# Default values
print(*(x for x in mylist), sep=' ')
# Output:
# a b c d e f g
# Changing all values
print(*(ord(x) for x in mylist), sep=' ') # ord() return a unicode code from a character
# Output:
# 97 98 99 100 101 102 103
# Changing just few values
print(*(x if x != 'c' else '_' for x in mylist), sep=' ')
# Output:
# a b _ d e f g