in operator for strings

M

Moosebumps

Wouldn't it be cool if you could do this?

('hello','test') in 'blah blah hello blah test':

and it would say if all elements of the list are in the string?

it would be more efficient and more readable than:

'hello' in 'blah blah hello blah test' and 'test' in 'blah blah hello blah
test'
 
F

Fredrik Lundh

Moosebumps said:
Wouldn't it be cool if you could do this?

('hello','test') in 'blah blah hello blah test':

and it would say if all elements of the list are in the string?

well, if you're asking me, I'd say that what's really cool is that you
can do not only

findall(('hello', 'test'), 'blah blah hello blah test')

but also

find_any(('hello', 'test'), 'blah blah hello blah test')

find_in_order(('hello', 'test'), 'blah blah hello blah test')

find_in_any_case(('hello', 'test'), 'blah blah hello blah test')

starts_and_ends_with(('hello', 'test'), 'blah blah hello blah test')

find_only_on_fridays(('hello', 'test'), 'blah blah hello blah test')

etc.

without having to change the language, or any of its implementations.

</F>
 
H

Heather Coppersmith

Wouldn't it be cool if you could do this?
('hello','test') in 'blah blah hello blah test':
and it would say if all elements of the list are in the string?
it would be more efficient and more readable than:
'hello' in 'blah blah hello blah test' and 'test' in 'blah blah hello blah
test'

Untested:

def string_contains_any_of( targets, the_string ):
for target in targets:
if target in the_string:
return True
return False

string_contains_any_of( ('hello', 'test'), 'blah blah blah' )

HTH,
Heather
 
L

Larry Bates

This can be written as:

a=('hello','test')
b='blah blah hello blah test'
reduce(lambda x,y: x and b.count(y), a)

or as a fuction:

def contains_all(a, b):
return reduce(lambda x,y: x and b.count(y), a)


Then in main program

if contains_all(a,b):
...

Larry Bates
Syscon, Inc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top