The Student Room Group

Searching for Pythons!

I was experimenting with searching in python and have come up with a method like this:
iinput = input("Search")
x = "xx"
y = "yy"
if iinput in x: print(x)
if iinput in y: print(y)

This works but, as you can imagine it takes a VERY LONG TIME.
Is there a quicker way to do this?
Reply 1
Original post by SamRob85
I was experimenting with searching in python and have come up with a method like this:
iinput = input("Search")
x = "xx"
y = "yy"
if iinput in x: print(x)
if iinput in y: print(y)

This works but, as you can imagine it takes a VERY LONG TIME.
Is there a quicker way to do this?


I don't get what you're trying to do here. Are you printing all the strings (x, y, ...) that contain the search term?
Reply 2
Original post by Damask-
I don't get what you're trying to do here. Are you printing all the strings (x, y, ...) that contain the search term?

If the search term is in any of the strings it will print that string out.
Reply 3
Original post by SamRob85
If the search term is in any of the strings it will print that string out.




strings = ["xx", "yy"]
searchTerm = raw_input("Search")

for string in strings:
if searchTerm in string
print string
Reply 4
Original post by Damask-

strings = ["xx", "yy"]
searchTerm = raw_input("Search")

for string in strings:
if searchTerm in string
print string

Do you know of a way to do this in python 3.3.3
Reply 5
Original post by SamRob85
Do you know of a way to do this in python 3.3.3


swap raw_input for input and print for print() and don't leave out the colon on the if statement as I appear to have done :colondollar:
Reply 6
You can use the in keyword.

my_list = ["apples","oranges","pears"]
if my_str in my_list: # my_str could be apples
print("Found string")
else:
print("Cannot find string")
Reply 7
Original post by Damask-
swap raw_input for input and print for print() and don't leave out the colon on the if statement as I appear to have done :colondollar:

This prints all of them but I would like it to only print out a specific string.
Reply 8
Original post by SamRob85
This prints all of them but I would like it to only print out a specific string.


No it won't, it will print all the ones that contain the search term. Is that not what you wanted?

Quick Reply

Latest

Trending

Trending