像在BASH中一样,我可以在循环中使用“ echo -n”,并在一行中打印数组(或Python中的列表)中的所有元素,而无需使用任何空格字符。有关循环,请参见下文的“ echo -n值”。
Arun Sangal@pc MINGW64 ~
$ a=(1 2 33 four)
Arun Sangal@pc MINGW64 ~
$ for v in ${a[@]}; do echo $v; done
1
2
33
four
Arun Sangal@pc MINGW64 ~
$ for v in ${a[@]}; do echo -n $v; done
1233four
Arun Sangal@pc MINGW64 ~
$ for v in ${a[@]}; do echo -n "$v "; done
1 2 33 four
在迭代每个列表值的同时,如何使用for循环在Python中执行相同的操作。
PS:我不想使用“” .join(list)。另外,似乎“” .join(list)仅在我的Python列表中的值为“字符串”类型时才有效,然后“” .join(list)将起作用(如BASH echo -n),但如果列表中为Integer aka非字符串值(例如:如下面代码中的列表编号所示),““。join(numbers)或”“ .join(str(numbers))仍然不起作用(如BASH echo -n); 在这种情况下,即使我使用了print num,在循环中,它仍然引入了空格字符“”。
我正在尝试使用打印值(通过命令),但是引入了空格“”字符。
在Python 2.x中,显示以下代码:
numbers = [7, 9, 12, 54, 99] #"".join(..) will NOT work or print val, will not work here
strings = ["1", "2", "33", "four"] #"".join(..) will work as values are strings type.
print "This list contains: "
#This will print each value in list numbers but in individual new line per iteration of the loop.
for num in numbers:
print num
print ""
print "".join(str(numbers))
print "".join(strings)
#PS: This won't work if the values are "non-string" format as I'm still getting a space character (see output below) for each print statement for printing num value
for num in numbers:
print num,
输出为:
This list contains:
7
9
12
54
99
[7, 9, 12, 54, 99]
1233four
7 9 12 54 99
我要寻找的是,当列表具有非字符串值时,如何在同一行中使用for循环和打印语句来打印列表编号的所有元素(如下所示)?
79125499
如果我理解的正确,您是否正在尝试打印数字而在它们之间没有空格?如果是这样,请尝试以下操作。
from __future__ import print_function
for i in range(1, 11):
print (i, end='')
结果
12345678910
Process finished with exit code 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句