我如何在字符串中搜索子串,然后在python中找到子串前的字符?

问题描述 投票:1回答:1

我正在用python做一个小项目,让你做笔记,然后通过使用特定的参数来读取它们。我试图做一个if语句来检查字符串中是否有逗号,如果有,那么我的python文件应该找到逗号,然后找到逗号下面的字符,并把它变成一个整数,这样就可以读出用户在特定的用户定义范围内创建的笔记。

如果这没有意义的话,那么基本上我要说的是,我想找出是哪一行代码导致了这一点没有工作,即使notes.txt有内容也没有返回。

这是我的python文件。

if "," not in no_cs: # no_cs is the string I am searching through
    user_out = int(no_cs[6:len(no_cs) - 1])
    notes = open("notes.txt", "r") # notes.txt is the file that stores all the notes the user makes
    notes_lines = notes.read().split("\n") # this is suppose to split all the notes into a list
    try:
        print(notes_lines[user_out])
    except IndexError:
        print("That line does not exist.")
        notes.close()
elif "," in no_cs:
    user_out_1 = int(no_cs.find(',') - 1)
    user_out_2 = int(no_cs.find(',') + 1)
    notes = open("notes.txt", "r")
    notes_lines = notes.read().split("\n")
    print(notes_lines[user_out_1:user_out_2]) # this is SUPPOSE to list all notes in a specific range but doesn't
    notes.close()

现在这里是notes. txt文件:

note
note1
note2
note3

最后,当我试图运行程序并输入notes(0,2)时,我在控制台得到的结果是:

>>> notes(0,2)
jeffv : notes(0,2)
[]
python-3.x substring
1个回答
2
投票

一个很好的方法是使用python .partition()方法。它的工作原理是将字符串从第一次出现的地方拆分出来,并返回一个元组...... 这个元组由三部分组成 0:分离器之前 1:分离器本身 2:分离器之后。

# The whole string we wish to search.. Let's use a 
# Monty Python quote since we are using Python :)
whole_string = "We interrupt this program to annoy you and make things\
                generally more irritating."

# Here is the first word we wish to split from the entire string
first_split = 'program'

# now we use partition to pick what comes after the first split word
substring_split = whole_string.partition(first_split)[2]

# now we use python to give us the first character after that first split word
first_character = str(substring_split)[0] 

# since the above is a space, let's also show the second character so 
# that it is less confusing :)
second_character = str(substring_split)[1]

# Output
print("Here is the whole string we wish to split: " + whole_string)
print("Here is the first split word we want to find: " + first_split)
print("Now here is the first word that occurred after our split word: " + substring_split)
print("The first character after the substring split is: " + first_character)
print("The second character after the substring split is: " + second_character)

输出

Here is the whole string we wish to split: We interrupt this program to annoy you and make things generally more irritating.
Here is the first split word we want to find: program
Now here is the first word that occurred after our split word:  to annoy you and make things generally more irritating.
The first character after the substring split is:  
The second character after the substring split is: t
© www.soinside.com 2019 - 2024. All rights reserved.