【问题标题】:Find Part of Substring from String then Show its Substring从字符串中查找子字符串的一部分然后显示它的子字符串
【发布时间】:2020-12-21 04:59:43
【问题描述】:

我有一个字符串“Halo Device ANumber:6232123123 Customer ID:16926”
我想用这个关键字搜索:“62”
然后如果有的话,我想显示它的整个子字符串“6232123123”

string = str('Halo Device ANumber : 6232123123 Customer ID : 16926')
ind = string.find('62')
word = string.split()[ind]

print('62 found in index: ', ind)
print('substring : ', word)

输出:

62 found in index:  22
substring : Device

【问题讨论】:

标签: python python-3.x


【解决方案1】:

如果您正在寻找一个特定的“完整字符串”,它以一个空格结束,您可以再次使用.find()

string = str('Halo Device ANumber : 6232123123 Customer ID : 16926')
target = '62'
ind = string.find(target)

ind_end = string.find(' ', ind + len(target))
word = string[ind:ind_end]

现在,如果您想要更健壮的东西,我们可以使用正则表达式:

string = str('Halo Device ANumber : 6232123123 Customer ID : 16926')
word = re.findall('(62\d+)', string).groups()[0]

这将从您的字符串中获取以“62”开头的第一个匹配项,并捕获所有剩余的数字。

【讨论】:

    猜你喜欢
    • 2011-04-14
    • 2012-09-07
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 2013-01-07
    • 2011-07-13
    相关资源
    最近更新 更多