Hello everyone! Q: There are several lines in txt, for example
'Карман-рукав?шов' 'Карман-рукав?чтото' 'Карман-рукав?чтотоеще'
I need to make a slice from each line of the part from the character – to the character ?, and assign it to a variable, but my method does not work. please tell me what is wrong:
srez = line ['-':'?']
Your method cannot work because a string can only be indexed by integers, not by other strings. Choice:
srez = line.split('?').split('-') srez = line[line.find('-')+1:line.find('?')]
I will add, about using
index instead of
find . If we modify the 2nd option as
srez = line[line.find('-'):line.find('?')][1:]
then the result in case of absence in the string
? and / or
- can be considered quite correct: in case of absence
- empty string will always be obtained, if not
? but there
- – a substring from
- to the end. Whether such a result is considered correct is up to the author of the question to decide, depends on the goals of finding the substring.
PS Throwing an exception for an "invalid" input string is a perfectly reasonable way to handle it.