python 如何拆分整数_如何在Python中将字符串拆分为整数?

I have a string "42 0" (for example) and need to get an array of the two integers. Can I do a .split on a space?

解决方案

6 answers is not nearly enough for a question that OP could easily have answered himself by testing in the interpreter:

>>> "42 0".split() # or .split(" ")

['42', '0']

A: Yes.

But it has not been specifically pointed out that the split method by default splits on whitespace (space, tab, carriage return and newline) if you do not supply an argument to it.

>>> " \r 42\n\r \t\n \r0\n\r\n".split()

['42', '0']

Also, using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int, float, str, etc. In Python 2:

>>> map(int, "42 0".split())

[42, 0]

In Python 3, map will return a lazy object, you can get it into a list with list(), or use as is in a for loop for example:

>>> map(int, "42 0".split())

>>> list(map(int, "42 0".split()))

[42, 0]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值