The following code takes a string such as abcd#1234, removes the '#' and splits it into abcd and 1234
import sys
import re
print("User ID: {0}").format(sys.argv[1])
print("User Type: {0}").format(sys.argv[2])
sub = re.sub('[#]', '', sys.argv[1])
split = re.match(r"([a-z]+)([0-9]+)", sub, re.I)
print(split.groups())
The output from print(split.groups())
is <'abcd', '1234'> How can I take an individual section of the split such as abcd and just output that?
split.group(1) # --> 'abcd'
split.group(2) # --> '1234'
Use index.
Ex:
s = "abcd#1234"
import re
sub = re.sub('[#]', '', s)
split = re.match(r"([a-z]+)([0-9]+)", sub, re.I)
print(split.groups()[0])
print(split.groups()[1])
Output:
abcd
1234
You can simply get the values of each as shown below:
data = split.groups()
if len(data) == 2:
name, id = data
print(name, id)
Or you can use group([group1, ...])
.
You can also use split directly and get just tell it to take the second element.
import sys
import re
string="abcd#1234"
string1=string.split("#")[1] # tells it to take the second element of the split
print(string1) # Prints 1234
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.