如何在Python中将字符串拆分为整数? [英] How to split a string into integers in Python?

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

问题描述

我有一个字符串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个答案通过在翻译:

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

答:是的。

但尚未明确指出拆分默认情况下,方法在空格上分割(空格,制表符,回车 换行符)如果您没有提供论据。

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中将字符串拆分为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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