简体   繁体   English

在同一行打印数字(Python)

[英]Print numbers on same line (Python)

I have a variable which give as output numbers taken from a list every loop.我有一个变量,它从每个循环的列表中给出输出数字。

idx = 0
for i in y:
        listbyte = subprocess.check_output('python foo.py ' + path + str(y[idx]), shell=True).rstrip()
        idx += 1
        listnum = listbyte.decode()
        number = (listnum[0])
        print(number)
        u.append(listnum)

If I print number , the output format is:如果我打印number ,输出格式为:

1
2
3
4
5

If I put end = '' at the end of the print, it works pretty well, outputing: 12345 .如果我把end = ''放在打印的末尾,它工作得很好,输出: 12345

The question is: how can I make this output a variable ?问题是:我怎样才能使这个输出成为一个变量? I have to use this format for some code ahead in the program but from what I see the end = '' argument is something restricted to print() function.我必须对程序中的某些代码使用这种格式,但从我看来, end = ''参数仅限于print()函数。

It should be something like this:它应该是这样的:

a = number(listnum[0])
print(a)

>>>12345

Thanks谢谢

EDIT: using Megabeets answer, the output now is:编辑:使用 Megabeets 答案,现在的输出是:

0
09
091
0912
09126
091265
0912655
09126554
091265548

You can use a += (listnum[0]) as you can see in the following example:您可以使用a += (listnum[0])如以下示例所示:

a = ''
idx = 0
for i in y:
        listbyte = subprocess.check_output('python foo.py ' + path + str(y[idx]), shell=True).rstrip()
        idx += 1
        listnum = listbyte.decode()
        a += (listnum[0])
        u.append(listnum)

And then a will be a string which contains "12345"然后a将是一个包含“12345”的字符串

>>> print(a)
12345

In case you want a to be an integer at the end, and not a string, you can parse it using int(a)如果您希望a最后是整数而不是字符串,则可以使用int(a)解析它

You can either store the numbers in a string and convert that to int or append to a list and join them later on.您可以将号码或者存储在一个string并转换,为int或追加到一个list ,并join以后他们。

Example for a list of numbers from [1,5] :来自[1,5]的数字列表的示例

Using a list ,使用list

>>> nums = []
>>> for i in range(1,6): 
        nums.append(i) 

>>> nums
=> [1, 2, 3, 4, 5]
>>> ''.join(str(x) for x in nums)
=> '12345'
>>> int(''.join(str(x) for x in nums))
=> 12345

Using a str使用str

>>> nums = ''
>>> for i in range(1,6): 
        nums+=str(i)

>>> nums
=> '12345'
>>> int(nums)
=> 12345

Or even do it without any conversions mathematically或者甚至在没有任何数学转换的情况下进行

>>> nums=0
>>> for i in range(1,6): 
        nums=(nums*10)+i 

>>> nums
=> 12345

打印 5 % (101 % 3) 和 (76 // 3) * 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM