i have a python list as follows
List=['\Opt\mydata.cab','\my\ginger','\my\garbage','\my\hfs']
i have a string as given below
strin1="mydata\opt\mydata.cab"
is there any easy way to match the string in list '\\Opt\\mydata.cab' one line without a for loop like given below
if strin1 in List:
print(strin1)
No, Python doesn't have anything like that. But you can always use any
function like this
if any(item in strin1 for item in List):
Still, this will look for exact match. If you want case-insensitive match you can convert both sides to lowercase.
The advantages of using any
are
You don't have to roll your own function
It short-circuits immediately when the condition is satisfied for the first time
It works with any iterable
If you want to get the item which matches, you can use the next
function like this
next(item for item in List if item in strin1)
You can also pass the default value to be returned if there is no match, like this
next(item for item in List if item in strin1, None)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.