【发布时间】:2017-05-20 05:07:59
【问题描述】:
我有数据:
audio_9813314_456239162
audio_9813314_456239175
audio_9813314_456239145
audio_9813314_456239178
我只需要数字的第二部分,比如
456239162
456239175
等
【问题讨论】:
我有数据:
audio_9813314_456239162
audio_9813314_456239175
audio_9813314_456239145
audio_9813314_456239178
我只需要数字的第二部分,比如
456239162
456239175
等
【问题讨论】:
如您所见,我循环遍历数据并将数据拆分到 _ 和最后一部分 [-1]
data = ["audio_9813314_456239162",
"audio_9813314_456239175",
"audio_9813314_456239145",
"audio_9813314_456239178"]
new_data = []
for i in data:
last_part = i.split("_")[-1]
new_data.append(last_part)
print(new_data)
输出:
['456239162', '456239175', '456239145', '456239178']
output:
【讨论】:
您在这里有几个选项,因此您可以选择其中一个。您可以通过以下两种方式获得它。
findall
如果你知道你需要的数字总是在末尾或第二个位置,你可以使用findall
import re
str1 = 'audio_9813314_456239162'
print re.findall('(\d+)', str1)[-1]
print re.findall('(\d+)', str1)[1]
输出
456239162
456239162
match 明确搜索术语
匹配从第一个字符开始,从左到右,因此您需要考虑到您要查找的数字之前的所有内容。注意:第 0 个索引是整个字符串,所以我们得到第 1 个索引。
print re.match('.+_\d+_(\d+)', str1).group(1)
【讨论】: