Reputation:
I'm trying to figure out a way to see if a character in a string before another one to get and output. Say:
v="Hello There"
x=v[0]
if "Hello" in x:
print("V consists of '"'Hello'"'")
if "There" in x:
print("Hello comes before There)
if "There" in x:
print("V consists of '"'There'"'")
if "Hello" in x:
print("There comes before Hello")
What I'm trying to get is "Hello comes before There", though it doesn't seem to work when I type it in. Help would be greatly appreciated.
The reason why the output would indicate that Hello comes before there is because the script is read from top to bottom, and this is just an exploit of that fact.
If any of this does not make any sense, please feel free to reach me in the answer section.
Upvotes: 2
Views: 6228
Reputation: 31
As Patrick mentioned, this works:
if s.find('There') < s.find('Hello'):
print('There comes before Hello')
However, this only works if both words are present in the string, otherwise their position would be -1 (i.e. 'There' is not present and therefore it will be -1 < s.find('Hello'), which would be always the case when 'There' is not present (except -1 < -1).
Here the code that would work in a more universal way:
if s.find('There') < s.find('Hello') and s.find('There') > 0:
print('There comes before Hello')
Upvotes: 2
Reputation: 1108
Assuming your needs are as simple as you have implied in the question details, then this should do -
v = "Hello There"
# Change s1 and s2 as you please depending on your actual need.
s1 = "Hello"
s2 = "There"
if s1 in v and s2 in v:
# Refer - https://docs.python.org/2/library/string.html#string.find
if v.find(s1) < v.find(s2):
print(s1 + " comes before " + s2)
else:
print(s2 + " comes before " + s1)
Upvotes: 0
Reputation: 5001
v="Hello There".split() #splitting the sentence into a list of words ['Hello', 'There'], notice the order stays the same which is important
#got rid of your x = v[0] since it was pointless
if "Hello" in v[0]: #v[0] == 'Hello' so this passes
print("V consists of '"'Hello'"'")
if "There" in v[1]: #v[1] == 'There' so this passes. This line had indentation errors
print("Hello comes before There") # This line had indentation errors
if "There" in v[0]: #v[0] == 'Hello' so this fails
print("V consists of '"'There'"'")
if "Hello" in v[1]: #v[1] == 'There' so this fails. This line had indentation errors
print("There comes before Hello") # This line had indentation errors
Fixed your code with some comments to show you what's happening and what not. You had indentation errors too.
If you want a better coding practice see Patrick's answer. I just wanted to show you what you were doing wrong
Upvotes: 0
Reputation: 61062
For string 's', s.find(substring)
returns the lowest index of s
that begins substring
if s.find('There') < s.find('Hello'):
print('There comes before Hello')
Upvotes: 9