Reputation: 67
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.
Upvotes: 1
Views: 69
Reputation: 2344
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])
Upvotes: 2
Reputation: 33335
# 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)
Upvotes: 1
Reputation: 77347
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'
Upvotes: 2
Reputation: 31
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
Upvotes: 0