R
R
Reikoni2021-08-01 20:32:00
Python
Reikoni, 2021-08-01 20:32:00

How to cut in a string from the desired character to the next LETTER?

For example, there is a string: "F34E72H7" .
I need to cut from the letter E to H, and select the number 72. Of course, it could have been done like this:

my = "F34E72H7"
print (my[my.index("E"):my[my.index("H")]) #72


But I need any letter instead of E and H, and it’s impossible to know this in advance when writing code.
And so that he selects absolutely the entire number, that is, instead of 72, there may be 7826 and he will select it.
Work example:
String: F56G7S Slice
: with letter F
Output: 56

String: G5293S982J Slice
: with letter S
Output: 982

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2021-08-01
@ifullut

re.search(f'{нужный_символ}(\d+)', string).group(1)

M
Michael, 2021-08-01
@lob4Noff

my = "G5293S982J"

start = input('Enter the start: ').upper() # S
end = input('Enter the end: ').upper() # J

try:
    result = my[(my.index(start)+1):my.index(end)] 
    print(result) # 982 
except:
    print('No matches!')

You can pass characters to the start and end variables, and the program will calculate the necessary interval itself.

M
MinTnt, 2021-08-01
@MinTnt

What you are describing is regular regular expressions (regex)

s = "F34E72H7"
import re

letterForStartSlice = "F"
search = re.search(letterForStartSlice + "(\d+)\w", s)
print(search.group(1))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question