[英]Print individual split strings
The following code takes a string such as abcd#1234, removes the '#' and splits it into abcd and 1234 以下代码采用字符串,例如abcd#1234,删除“#”并将其拆分为abcd和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? print(split.groups())
的输出为<'abcd','1234'>如何获取拆分的单个部分(例如abcd)并仅输出呢?
split.group(1) # --> 'abcd'
split.group(2) # --> '1234'
https://docs.python.org/3/library/re.html#re.match.group https://docs.python.org/3/library/re.html#re.match.group
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, ...])
. 或者,您可以使用
group([group1, ...])
。
You can also use split directly and get just tell it to take the second element. 您也可以直接使用split并告诉它采用第二个元素。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.