简体   繁体   中英

Python How to pick a character that can change from a string

If I have this string "for[4t]" and I want to pick "4" . But the number can change : the string can be "for[12t]" , "for[342424t]" , ect.. how I pick this number?

I can't use str.replace('for[', '').replace('t]') , because the rest of the string after this can change.

You can get the variable with a regular expression. In this example, "for[" and "t]" are constant, and you want a variable number of digits inside. In a regular expression, [ is a special character so needs to be escaped. () selects a group of characters you want to capture, and \d+ says "any number of digits (but at least one)".

>>> import re
>>> test = "for[4t]"
>>> re.match(r"for\[(\d+)t]", test).group(1)
'4'
>>> test = "for[342424t]"
>>> re.match(r"for\[(\d+)t]", test).group(1)
'342424'
>>> test = "for[342424t] and other stuff"
>>> re.match(r"for\[(\d+)t]", test).group(1)
'342424'

Here is a way to do it

import re

strings = ["for[4t]", "for[12t]", "for[342424t]"]
for string in strings:        
    print(re.findall(r"for\[([0-9]+)t", string)[0])
# define some sample message
message = "hello for[555t] goodbye"

# find the first [
bracket_location = message.find("[")

# declare a variable for picking the number
pick_number = ''

# loop over the contents of message, starting one character past
# the bracket
for ch in message[bracket_location+1:]:
    # if this is not a digit, break the loop
    if not ch.isdigit():
        break

    # add this digit to the pick number
    pick_number += ch

# we're done, print the number we picked
print(pick_number)

lets say the variable string holds the string, and the variable number will hold the number that you want.

if you wat number to have type string:

number = string[string.index("[")+1:string.index("t]")]

if you want number to have type integer:

number = int(string[string.index("[")+1:string.index("t]")])

This only works if the number is between [ and t] , and if those are the first two instances of [ and t] in the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM