473,382 Members | 1,752 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

searching for strings (in a tuple) in a string

Hi,

I often use:

a='yy'
tup=('x','yy','asd')
if a in tup:
<...>

but I can't find an equivalent code for:

a='xfsdfyysd asd x'
tup=('x','yy','asd')
if tup in a:
< ...>

I can only do:

if 'x' in a or 'yy' in a or 'asd' in a:
<...>

but then I can't make the if clause dependent on changing value of tup.

Is there a way around this?

Jul 6 '06 #1
7 1159
You can get the matching elements with a list comprehension with
something like

pya='xfsdfyysd asd x'
pytup=('x','yy','asd')
py[x for x in tup if x in a.split()]
['x', 'asd']

Hope this helps

manstey wrote:
Hi,

I often use:

a='yy'
tup=('x','yy','asd')
if a in tup:
<...>

but I can't find an equivalent code for:

a='xfsdfyysd asd x'
tup=('x','yy','asd')
if tup in a:
< ...>

I can only do:

if 'x' in a or 'yy' in a or 'asd' in a:
<...>

but then I can't make the if clause dependent on changing value of tup.

Is there a way around this?
Jul 6 '06 #2
"manstey" <ma*****@csu.edu.auwrote:
but I can't find an equivalent code for:

a='xfsdfyysd asd x'
tup=('x','yy','asd')
if tup in a:
< ...>

I can only do:

if 'x' in a or 'yy' in a or 'asd' in a:
<...>

but then I can't make the if clause dependent on changing value of tup.

Is there a way around this?
is the "def" statement broken in your Python version ?

def findany(text, words):
for w in words:
if w in text:
return True
return False

if findany(a, tup):
...

</F>

Jul 6 '06 #3
I know I can do it this way. I wanted to know if there was another way.

Fredrik Lundh wrote:
"manstey" <ma*****@csu.edu.auwrote:
but I can't find an equivalent code for:

a='xfsdfyysd asd x'
tup=('x','yy','asd')
if tup in a:
< ...>

I can only do:

if 'x' in a or 'yy' in a or 'asd' in a:
<...>

but then I can't make the if clause dependent on changing value of tup.

Is there a way around this?

is the "def" statement broken in your Python version ?

def findany(text, words):
for w in words:
if w in text:
return True
return False

if findany(a, tup):
...

</F>
Jul 6 '06 #4
"manstey" <ma*****@csu.edu.auwrote:
>I know I can do it this way. I wanted to know if there was another way.
if you don't want to write Python programs, why are you using Python ?

</F>

Jul 6 '06 #5
manstey wrote:
Hi,

I often use:

a='yy'
tup=('x','yy','asd')
if a in tup:
<...>

but I can't find an equivalent code for:

a='xfsdfyysd asd x'
tup=('x','yy','asd')
if tup in a:
< ...>

I can only do:

if 'x' in a or 'yy' in a or 'asd' in a:
<...>

but then I can't make the if clause dependent on changing value of tup.

Is there a way around this?
One thing I do sometimes is to check for True in a generator
comprehension

if True in (t in a for t in tup):
# do whatever here
Because you're using a generator you get the same "short-circut"
behavior that you would with a series of 'or's, the if statement won't
bother checking the rest of the terms in tup after the first True
value.
>>def f(n, m):
print n
return n m
>>m = 2
if True in (f(n, m) for n in range(5)):
print 'done'
0
1
2
3
done

# See? No 4! :-)
I usually use this with assert statements when I need to check a
sequence. Rather than:

for something in something_else: assert expression

I say

assert False not in (expression for something in something_else)

This way the whole assert statement will be removed if you use the '-O'
switch to the python interpreter. (It just occurred to me that that's
just an assumption on my part. I don't know for sure that the
interpreter isn't smart enough to remove the first form as well. I
should check that. ;P )

Note, in python 2.5 you could just say

if any(t in a for t in tup):
# do whatever here
In your case though, if I were doing this kind of thing a lot, I would
use a little helper function like the findany() function Fredrik Lundh
posted.

IMHO

if findany(a, tup):
...

is much clearer and readily understandable than mucking about with
generator comprehensions...
Peace,
~Simon

Jul 6 '06 #6
On Thu, 06 Jul 2006 04:45:35 -0700, manstey wrote:
Hi,

I often use:

a='yy'
tup=('x','yy','asd')
if a in tup:
<...>

but I can't find an equivalent code for:

a='xfsdfyysd asd x'
tup=('x','yy','asd')
if tup in a:
< ...>
Of course you can't. Strings don't contain tuples, since they are utterly
different kinds of objects.
I can only do:

if 'x' in a or 'yy' in a or 'asd' in a:
<...>

but then I can't make the if clause dependent on changing value of tup.
Sure you can.

a = 'xfsdfyysd asd x'
tup = ('x','yy','asd')
for item in tup:
if item not in a:
print "Item missing"
break
else:
print "All items found."

It's a little verbose, but you can stick it into a function definition and
use it as a one-liner.

Or, use a list comprehension:

a = 'xfsdfyysd asd x'
tup = ('x','yy','asd')
if [item for item in tup if item in a]:
print "Some items found."
else:
print "No items found."

Or, you can use filter:

a = 'xfsdfyysd asd x'
tup = ('x','yy','asd')
if filter(lambda item, a=a: item in a, tup):
print "Some items found."
else:
print "No items found."
However, keep in mind that "in" has a subtly different effect in strings
and tuples.

"x" in ("x", "y") is true, but "x" in ("xy", "yy") is not, as you would
expect. However, the situation for strings isn't quite the same:
"x" in "x y" is true, but so is "x" in "xx yy".

One way around that is to convert your string a into a list:

a = 'xfsdfyysd asd x'
a = a.split() # split on any whitespace

and now your tests will behave as you expected.

--
Steven.

Jul 7 '06 #7
Simon Forman wrote:
....
I usually use this with assert statements when I need to check a
sequence. Rather than:

for something in something_else: assert expression

I say

assert False not in (expression for something in something_else)

This way the whole assert statement will be removed if you use the '-O'
switch to the python interpreter. (It just occurred to me that that's
just an assumption on my part. I don't know for sure that the
interpreter isn't smart enough to remove the first form as well. I
should check that. ;P )
FWIW I did just check that and it seems valid, the second form gets
"optimized" away.

File delme.py:
import dis

N = (True, True, False)

def a():
for n in N:
assert n

def b():
assert False not in (n for n in N)

dis.dis(a)
print '==============================='
dis.dis(b)
Results of running it without '-O':
$ python delme.py
8 0 SETUP_LOOP 28 (to 31)
3 LOAD_GLOBAL 0 (N)
6 GET_ITER
> 7 FOR_ITER 20 (to 30)
10 STORE_FAST 0 (n)

9 13 LOAD_FAST 0 (n)
16 JUMP_IF_TRUE 7 (to 26)
19 POP_TOP
20 LOAD_GLOBAL 2 (AssertionError)
23 RAISE_VARARGS 1
> 26 POP_TOP
27 JUMP_ABSOLUTE 7
> 30 POP_BLOCK
31 LOAD_CONST 0 (None)
34 RETURN_VALUE
===============================
13 0 LOAD_GLOBAL 0 (False)
3 LOAD_CONST 1 (<code object <generator
expressionat 0xb7d89ca0, file "delme.py", line 13>)
6 MAKE_FUNCTION 0
9 LOAD_GLOBAL 1 (N)
12 GET_ITER
13 CALL_FUNCTION 1
16 COMPARE_OP 7 (not in)
19 JUMP_IF_TRUE 7 (to 29)
22 POP_TOP
23 LOAD_GLOBAL 2 (AssertionError)
26 RAISE_VARARGS 1
> 29 POP_TOP
30 LOAD_CONST 0 (None)
33 RETURN_VALUE
Results of running it with '-O':
$ python -O delme.py
8 0 SETUP_LOOP 14 (to 17)
3 LOAD_GLOBAL 0 (N)
6 GET_ITER
> 7 FOR_ITER 6 (to 16)
10 STORE_FAST 0 (n)

9 13 JUMP_ABSOLUTE 7
> 16 POP_BLOCK
17 LOAD_CONST 0 (None)
20 RETURN_VALUE
===============================
13 0 LOAD_CONST 0 (None)
3 RETURN_VALUE

Jul 14 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Sims | last post by:
Hi, Given a string $txt and an array of strings $txt_array what would be the best/fastest way to search in _insensitive_ case if $txt is in $text_array and, if it is, where is it? Because I...
3
by: hokiegal99 | last post by:
How do I say: x = string.find(files, 'this', 'that', 'the-other') currently I have to write it like this to make it work: x = string.find(files, 'this') y = string.find(files, 'that') z =...
4
by: tgiles | last post by:
Hi, all. Another bewildered newbie struggling with Python goodness. This time it's searching strings. The goal is to search a string for a value. The string is a variable I assigned the name...
1
by: Joeyej | last post by:
Hi - Wondering if anyone knows how to code a function fieldcheck to prevent users from choosing the same date from dual drop list on my web form using this include file example; <option...
6
by: JSheble | last post by:
I realise .NET has all these great objects, specifically strings, but is it really necessary to create a string variable (object) just to compare two string values? For example, I'm looking at...
35
by: Cor | last post by:
Hallo, I have promised Jay B yesterday to do some tests. The subject was a string evaluation that Jon had send in. Jay B was in doubt what was better because there was a discussion in the C#...
1
by: warheart | last post by:
hi im kinda new to programming i aint lazy to search and learn :D but i am getting despirate... ive been looking everywhere for a code to search a txt file and find a string, and then give...
1
by: DLN | last post by:
Hello all, I have a quick question regarding how best to use static strings in my C# code that I'm hoping someone can help me with. Is there any advantage/disadvantage from a performance...
3
by: Paul73 | last post by:
This is driving me nuts. Someone please help me with this. I have a program that's reading a list of terms to search for. The .IndexOf works fine if the term being searched for is in the first...
12
by: Alexnb | last post by:
This is similar to my last post, but a little different. Here is what I would like to do. Lets say I have a text file. The contents look like this, only there is A LOT of the same thing. () A...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.