Как мне найти подстроку в строке, а затем найти символ перед подстрокой в ​​python - PullRequest
1 голос
/ 09 мая 2020

Я делаю небольшой проект в python, который позволяет вам делать заметки, а затем читать их, используя определенные c аргументы. Я попытался сделать оператор if, чтобы проверить, есть ли в строке запятая, и если это так, то мой файл python должен найти запятую, затем найти символ прямо под этой запятой и превратить его в целое число, чтобы он мог зачитайте заметки, созданные пользователем в определенном c определяемом пользователем диапазоне.

Если это не имело смысла, то в основном все, что я говорю, это то, что я хочу узнать, какая строка / бит кода приводит к тому, что это не работает и ничего не возвращает, хотя в файле 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()

А вот и примечания. txt:

note
note1
note2
note3

и, наконец, вот что я получаю в консоли, когда пытаюсь запустить программу и набираю примечания (0,2)

>>> notes(0,2)
jeffv : notes(0,2)
[]

1 Ответ

2 голосов
/ 09 мая 2020

Отличный способ сделать это - использовать метод 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...