[英]What is the most pythonic way to remove characters from a string and create substrings?
Let's say we have this string: SIC0575(1, 2)
假设我们有这个字符串: SIC0575(1, 2)
SIC0575
length = 7, but it could dynamically change, so let's assume length = N SIC0575
长度 = 7,但它可以动态变化,所以我们假设长度 = N
(1, 2)
let's assume (0~9, 0~9) (1, 2)
假设 (0~9, 0~9)
I would like to create substrings from this string.我想从这个字符串创建子字符串。
Desired result:期望的结果:
val1 = SIC0575
val2 = 1
val3 = 2
I am not familiar with Python, I would like to know which is the most elegant/pythonic way to achieve that.我不熟悉 Python,我想知道哪种方式是最优雅的/pythonic 方式来实现这一点。 Is there any built-in function to do that?有没有内置的 function 可以做到这一点?
What I've tried (it works, but it's not elegant at all):我尝试过的(它有效,但一点也不优雅):
data = "SIC0575(1, 2)"
aux = data.split("(")
val1 = aux[0]
aux2 = aux[1].split(",")
val2 = aux2[0]
val3 = aux2[1][:-1]
regexes are your friend:正则表达式是你的朋友:
import re
s = "SIC0575(1, 2)"
val1, val2, val3 = re.fullmatch(r"(.*?)\((\d), (\d)\)", s).groups()
For your use case, I'd go with index
对于您的用例,我将 go 与index
Get the index
of opening parenthesis (
, and take the first slice for aux
, and use ast
for val1
, val2
获取左括号(
的index
,并取第一个切片为aux
,并使用ast
为val1
, val2
import ast
data = "SIC0575(1, 2)"
index = data.find('(')
aux = data[:index]
val1, val2 = ast.literal_eval(data[index:])
OUTPUT : OUTPUT :
print(aux, v1, v2)
SIC0575 1 2
I would go for something like below.我会 go 如下所示。
import re
stringEx = [_.replace(' ','') for _ in re.split('\)|\(|,',"SIC0575(1, 2)")[:-1]]
var1,var2,var3 = string[0],int(stringEx[1]),int(stringEx[2])
out出去
val1 = SIC0575
val2 = 1
val3 = 2
You can use a regular expression to match the strings.您可以使用正则表达式来匹配字符串。
import re
data = "SIC0575(1, 2)"
pattern = re.compile(r'(.*)\(([0-9]), ([0-9])\)')
val1, val2, val3 = pattern.match(data).groups()
print(val1, val2, val3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.