0

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?

1
  • print(split.groups()[0]) ? Commented May 11, 2018 at 10:01

4 Answers 4

1
split.group(1) # --> 'abcd'
split.group(2) # --> '1234'

https://docs.python.org/3/library/re.html#re.match.group

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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, ...]).

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.