繁体   English   中英

python如何在字符串中查找数字的完全匹配

[英]python how to find exact match of a number in a string

如何匹配字符串列表中的整数?

我的代码如下:

test_number = 123 # some number 1-399
lst = ["XXXXXXX-123_xxxxxxx",
       "XXXXXXX-399_xxxxxxx", ...]
# lst[0] should match, lst[1] should not

我需要做的是,如果test_number出现在lst任何字符串中,我需要对该字符串执行操作。

我是否使用re.search 但是search比较字符串,我的test_number是整数。

如果您知道它将完全按照这种方式格式化,请尝试以下操作,而不要使用正则表达式:

test_number = 307

your_list = ["ABC109$-307_letters##", "XYZ876%-100_numbers!"]

for value in your_list:
    if "-" + str(test_number) + "_" in value:
    # equivalently: "-{}_".format(str(test_number))
        # do something with that value

但是,如果不确定不确定目标值的周围是-_ ,则应使用正则表达式。 不幸的是,在那种情况下,很难说出您的模式应该是什么,因为我不知道这种情况。

使用与亚当·史密斯(Adam Smith)相同的假设(您的字符串将完全这样格式化),您应该在搜索数字之前先去除字符串的开头和结尾:

test_number = 123
for elem in your_list:
    if str(test_number) == elem[8:-8]:
        # match - do something
import re
test_number = 123
str1="XXjdasjXX-123_dsajdfs"
x= re.search("{}".format(test_number),str1).group()
print (x)

输出:

>>> 
123
>>> 

使用search查找匹配项和format以放置我们的电话号码。 然后使用group()将其从object转换为str。

如果要将其用作整数,请在打印之前将x=int(x)添加为整数,然后将其转换为整数!

您可以做类似的事情。

def checkInt(value):
    try:
        int(value)
        return True
    except ValueError:
        return False

test_num = 123
x = "XXXX-123_xxx"
y = x.split("-")
z = y[1].split("_")
if checkInt(z[0]) == True:
    num = int(z[0])
    if num == test_num:
        ####do something ####

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM