简体   繁体   English

如何在for循环中打印整数?

[英]How to print integer in a for-loop?

In Python, how do I print integer one below the other:在 Python 中,如何在另一个下方打印整数:

a1 = "Great"
a2 = 100
for all in a1:
    print(all)

Output:输出:

G
r
e
a
t

Question: How do I write for / print statement for the variable a2 , so that my output will be:问题:如何为变量a2编写for / print语句,以便我的输出为:

1
0
0

? ?

An object of type int is not iterable. int类型的对象不可迭代。 So force it to be iterable by making it a string .因此,通过使其成为string来强制它是可迭代的。

x = 1337
for num in str(x):
  print(num)

You need to convert a2 , an int into something that is iterable.您需要将a2 ,一个 int 转换为可迭代的东西。 One way you could do this is by converting a2 into a string:一种方法是将a2转换为字符串:

a2 = 100
for str_digit in str(a2): # if a2 is negative use str(a2)[1:] to not print '-' sign
    print(str_digit)

And another way could be by extracting the individual digits (still as ints) from a2 into a list (or another iterable):另一种方法是将a2的单个数字(仍为整数)提取到列表(或另一个可迭代对象)中:

def get_digits(num):
    num = abs(num)
    digits = []
    while num != 0:
        digits.append(num % 10)
        num //= 10
    return digits

a2 = 100
for str_digit in get_digits(a2):
    print(str_digit)

Output:输出:

1
0
0

To get letters of a word or elements of a number by a for loop you need a string要通过 for 循环获取单词的字母或数字的元素,您需要一个字符串

a = 100 is an integer so you need to convert it to a string like below : a = 100 是一个整数,因此您需要将其转换为如下所示的字符串


a=str(100)
for i in a:
    print(i)


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

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