如何将一串用空格分隔的数字拆分为整数? [英] How to split a string of space separated numbers into integers?

查看:246
本文介绍了如何将一串用空格分隔的数字拆分为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串"42 0"(例如),需要获取两个整数的数组.我可以在空格上做一个.split吗?

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?

推荐答案

使用 str.split() :

>>> "42 0".split()  # or .split(" ")
['42', '0']

请注意,在这种情况下,str.split(" ")是相同的,但是如果一行中有多个空格,则行为会有所不同.同样,.split()会在所有空格上分割,而不仅仅是空格.

Note that str.split(" ") is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.

当您要将可迭代项转换为诸如intfloatstr之类的内置项时,使用map通常看起来比使用列表理解更简洁.在Python 2中:

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]

在Python 3中,map将返回一个惰性对象.您可以使用list()将其放入列表:

In Python 3, map will return a lazy object. You can get it into a list with list():

>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]

这篇关于如何将一串用空格分隔的数字拆分为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆