[英]How can i read defined values from a string in python, like i can do in C with scanf
我有一个字符串,其格式如下 str="R%dC%d" 例如 Str=R150C123 并且我想将数值保存在变量中,例如在 C 语言中,如下所示:
int c,r;
sscanf(Str,"R%dC%d",&r,&c);
在 python 我这样做
c = int(str[str.find("C") + 1:])
r = int(str[:str.find("C")])
在 python 中是否有其他方法可以做到这一点,类似于我在 C 中的做法?
因为我在 python 中的方式需要很长时间才能执行。
另一种字符串格式的另一个示例是:Str="%[AZ]%d",例如 Str= ABCD1293
我想保存 2 个值,第一个是数组或字符串,第二个是数字
在 C 我这样做:
int r;
char CC[2000];
sscanf(s,"%[A-Z]%d",CC,&r)
在 Python 中像这样:
for j in x:
if j.isdigit():
r = x[x.find(j):]
CC= x[:x.find(j)]
break
我不认为这是在 python 中解决此类任务的一种优雅方式。 你能帮我么?
正如 Seb 所说,正则表达式!
import re
regex = r"R(\d+)C(\d+)"
test_str = "R150C123"
match_res = re.fullmatch(regex, test_str)
num_1, num_2 = match_res.groups()
num_1 = int(num_1)
num_2 = int(num_2)
您也可以使用正则表达式在单行中执行此操作:
import re
s = 'R150C123'
r,c = list(map(int,re.findall('\d+',s)))
re.findall function 创建嵌入在字符串中的所有数字的列表 map(int,...) function 将每个匹配的数字转换为 int 最后列表将整数作为列表返回,允许在一个赋值中定义 r&c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.