如果在另一个字符之前找到字符串中的字符

时间:2016-10-18 18:42:01

标签: python string variables if-statement

我正在试图找出一种方法来查看字符串中的字符是否在另一个字符串之前得到并输出。说:

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")

我想要的是“你好来之前”,虽然它在我输入时似乎不起作用。非常感谢帮助。

输出表明Hello之前是因为脚本是从上到下读取的原因,这只是对这一事实的利用。

如果其中任何一项没有任何意义,请随时在答案部分与我联系。

4 个答案:

答案 0 :(得分:5)

对于字符串'',s.find(substring)返回s的最低索引substring

if s.find('There') < s.find('Hello'):
    print('There comes before Hello')

答案 1 :(得分:0)

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

通过一些评论修正了您的代码,以向您展示正在发生的事情以及未发生的事情。你也有缩进错误。

如果您想要更好的编码练习,请参阅Patrick的回答。我只是想告诉你你做错了什么

答案 2 :(得分:0)

假设您的需求与问题详细信息中隐含的一样简单,那么应该这样做 -

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)

答案 3 :(得分:0)

帕特里克提到,这有效:

if s.find('There') < s.find('Hello'):
    print('There comes before Hello')

然而,这仅在字符串中存在两个单词时才有效,否则它们的位置将为-1(即'那里'不存在,因此它将为-1&lt; s.find('Hello'),当'There'不存在时(除了-1&lt; -1)之外,情况总是如此。

这里的代码将以更通用的方式工作:

if s.find('There') < s.find('Hello') and s.find('There') > 0:
    print('There comes before Hello')