【发布时间】:2009-10-10 02:13:21
【问题描述】:
为什么需要在下面的代码中使用函数'str'?
我正在尝试计算数字中的数字总和。
我的代码
for i in number:
sum(map(int, str(i))
其中 number 是下面的数组
[7,79,9]
我阅读我的代码如下
- 遍历数组,这样
- 整数位数的总和
- 通过map越来越多地获得数字中的数字
- 这样每个对象(给定的数字)都被转换为字符串//这没有意义
手册说 str
Type: type
Base Class: <type 'type'>
String Form: <type 'str'>
Namespace: Python builtin
Docstring:
str(object) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
【问题讨论】:
-
这段代码你需要明白的是,字符串是字符序列,map() 也是这样做的。
-
哦,那 int('5') 将返回整数 5。