[英]How to convert numbers and letters a string in a list into integers?
I'm trying to convert this list 我正在尝试转换此列表
a = ['45 inches', '45 inches', '44 inches', '42 inches', '41 inches', '41 inches']
into 进入
a = ['45', '45', '44', '42', '41', '41']
Could someone please help me figure this out? 有人可以帮我解决这个问题吗?
Depends on your condition of convertion. 取决于您的of依条件。 If you want to get only the item after by splitting, try :
如果您只想拆分后得到物品,请尝试:
a1 = [k.split()[0] for k in a]
If you want to find all numeric charcaters, try : 如果要查找所有数字字符,请尝试:
a2 = [''.join([m for m in k if m.isnumeric()]) for k in a]
using Regex: 使用正则表达式:
import re
a = ['45 inches','45 inches','44 inches','42inches','41inches','41inches']
res = []
for i in a:
m = re.search(r"\b(\d{2})\b", i)
if m:
res.append(m.group())
print(res)
One possibility is to use regular expressions to search for groups of digits within the strings. 一种可能是使用正则表达式在字符串中搜索数字组。
import re
a = ['45 inches', '45 inches', '44 inches', '42 inches', '41 inches', '41 inches']
out = []
for string in a:
nums = re.search(r"(\d+)", string)
if nums:
out.append(nums.group(1))
print(out)
# ['45', '45', '44', '42', '41', '41']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.