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

2024-04-24 02:49:20 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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在前面的原因是脚本是从上到下读取的,这只是对这个事实的一个利用。在

如果这些没有任何意义,请随时联系我的答案部分。在


Tags: of方法字符串in脚本helloif原因
3条回答

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

if s.find('There') < s.find('Hello'):
    print('There comes before Hello')
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

用一些注释修正了你的代码,告诉你发生了什么,什么没有发生。你也有缩进错误。在

如果你想要一个更好的编码实践,看看帕特里克的答案。我只是想告诉你你做错了什么

假设你的需求和你在问题细节中暗示的一样简单,那么这应该可以-

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)

相关问题 更多 >