检查以确保字符串不包含多个值 [英] Check to ensure a string does not contain multiple values

查看:75
本文介绍了检查以确保字符串不包含多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

**注意 - 我将不只是在一个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))
真正
 

否则:

 >>>进口重
>>> 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')

这篇关于检查以确保字符串不包含多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆