简体   繁体   English

Python类型转换

[英]Python type casting

I try to iterate over some number using Python 3. To do so I thought about casting the number to string. 我尝试使用Python 3遍历一些数字。为此,我考虑了将数字转换为字符串。 Simplified version is here: 简化版本在这里:

def printValue(num):
    value = str(num)
    for i in len(value):
        print(value[i])
    return;

However though I get info that int is not iterable: 但是,尽管我得到的信息是int不可迭代的:

Traceback (most recent call last):                                                                                                                                                                                                
  File "main.py", line 9, in <module>                                                                                                                                                                                             
    print(printValue(12112121))                                                                                                                                                                                       
  File "main.py", line 5, in printValue
    for i in len(value):                                                                                                                                                                                                          
TypeError: 'int' object is not iterable  

What do I do wrong? 我做错了什么?

len returns an integer, and you can't iterate over an integer. len返回一个整数,您不能迭代一个整数。

If you want to iterate over the range of integers from 0 up to len(value) , use range . 如果要迭代从0到len(value)的整数range ,请使用range

for i in range(len(value)):

Although in this case you don't really need the indices, so you may as well just iterate directly over the string's characters. 尽管在这种情况下,您实际上并不需要索引,所以也可以直接在字符串的字符上进行迭代。

for c in value:

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

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