简体   繁体   English

Python-如何将包含多个数字的字符串转换为int?

[英]Python - How do I convert a a string containing more than one number to an int?

How can I convert a string containing more than one number to an int in python, for example: "100, 200, 300" and "400, 500" . 如何将包含多个数字的字符串转换为python中的int,例如: "100, 200, 300""400, 500" I know how I can convert a string containing a single number such as "100" or "56" to an int but not a string which contains 2 numbers. 我知道如何将包含单个数字(例如"100""56"的字符串转换为int,但不能将包含2个数字的字符串转换为int。

Does anyone know how this could be done? 有谁知道该怎么做?

Thank you so much for your help. 非常感谢你的帮助。

Using map() for mapping list element to int 使用map()将列表元素映射到int

x = "100, 200, 300"
list(map(int, x.split(",")))

Output: 输出:

[100, 200, 300]

You can also use list comprehensions : 您还可以使用列表推导

In [635]: x = "100, 200, 300"
In [638]: results = [int(i) for i in x.split(',')]

In [639]: results
Out[639]: [100, 200, 300]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何替换字符串中的多个字符 Python - How do I replace more than one character in a string Python 如何拆分包含多个列表的字符串? python - how to split a string containing more than one list? python 如何将多个数字转换为字母? - How to convert more than one number into letters? Python:如何将int转换为具有一定位数的字符串表示形式? - Python: How do I convert an int to its string representation with a set number of digits? 如何在字符串中找到多于一个子字符串的位置(Python 3.4.3 shell) - How do i find the position of MORE THAN ONE substring in a string (Python 3.4.3 shell) 如何在python / numpy中将包含条目[[[int int]]…]的向量转换为包含条目[[int int]…]的向量? - How can I convert a vector containing entries [[[int int]] …] into a vector containing entries [[int int] …] in python/numpy? 如何在 Python 中将字符串转换为 int? - How can I convert a string to an int in Python? 如何在python中将字符串转换为唯一的十进制数字? - How do I convert a string into a unique decimal number in python? 如何将数字转换为与python中输入格式相同的字符串? - How do I convert a number to a string in the same format as the input in python? 如何将字符串转换为十进制数以在 Python 中进行算术运算? - How do I convert a string into a decimal number for arithmetic manipulation in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM