检查以确保字符串不包含多个值多个、字符串、不包含、以确保

2023-09-11 01:57:08 作者:蓝眼睛不忧郁

**注意 - 我将不只是在一个string--需要在字符串中的任何位置查找特定的子字符串结束测试

什么是检查,以确保一个字符串不包含多个值的最快方法。我现在的方法是低效和unpythonic:

 如果string.find(PNG)==  -  1和sring.find(JPG)==  -  1和string.find(GIF)==  - 1 string.find(YouTube的)== -1:
 

解决方案

如果你正在测试的串刚结束,请记住,str.endswith可以接受一个元组。

 >>> test.png.endswith((JPG,PNG,GIF))
真正
 
EXCEL中符合查询条件的字符串相加

否则:

 >>>进口重
>>> re.compile('JPG | PNG | GIF),搜索(testpng.txt)。
<在0xb74a46e8&GT _sre.SRE_Match对象;
>>> re.compile('JPG | PNG | GIF),搜索(testpg.txt)。
 

**Note- I will not just be testing at the end of a string-- need to locate particular substrings anywhere in the string

What is the fastest way to check to make sure a string does not contain multiple values. My current method is inefficient and unpythonic:

if string.find('png') ==-1 and sring.find('jpg') ==-1 and string.find('gif') == -1 and string.find('YouTube') == -1:

解决方案

if you're testing just the end of the string, remember that str.endswith can accept a tuple.

>>> "test.png".endswith(('jpg', 'png', 'gif'))
True

otherwise:

>>> import re
>>> re.compile('jpg|png|gif').search('testpng.txt')
<_sre.SRE_Match object at 0xb74a46e8>
>>> re.compile('jpg|png|gif').search('testpg.txt')