问题描述
我有一个字符串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?
推荐答案
6个答案通过在 和 )如果您没有提供论据。
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']
此外,使用 map
通常看起来比使用列表推导更清晰当你想将iterables项转换为内置函数时,如 int
, float
, str
等。在Python 2中:
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]
在Python 3中, map
将返回一个惰性对象,你可以使用 list()
将其输入到列表中,或者在中用于
循环,例如:
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())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]
这篇关于如何在Python中将字符串拆分为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!