简体   繁体   English

我如何从 python 中的字符串中读取定义的值,就像我可以在 C 中使用 scanf 一样

[英]How can i read defined values from a string in python, like i can do in C with scanf

I have a String, which is formatted as following str="R%dC%d" for example Str=R150C123 and i want to save the numeric values in a variable for example in C Language this would be as following:我有一个字符串,其格式如下 str="R%dC%d" 例如 Str=R150C123 并且我想将数值保存在变量中,例如在 C 语言中,如下所示:

int c,r;
sscanf(Str,"R%dC%d",&r,&c);

in python i do it like this在 python 我这样做

c = int(str[str.find("C") + 1:])
r = int(str[:str.find("C")])

is there any other way to do this in python similler to how i've done it in C?在 python 中是否有其他方法可以做到这一点,类似于我在 C 中的做法?

because my way in python takes a to much time to execute.因为我在 python 中的方式需要很长时间才能执行。

another example for another String format is: Str="%[AZ]%d", for example Str= ABCD1293另一种字符串格式的另一个示例是:Str="%[AZ]%d",例如 Str= ABCD1293

i want to save 2 values, the first one is an Array or a String and the second one is the numbers我想保存 2 个值,第一个是数组或字符串,第二个是数字

in C i do it like this:在 C 我这样做:

int r;
char CC[2000];
sscanf(s,"%[A-Z]%d",CC,&r)

in Python like this:在 Python 中像这样:

        for j in x:
            if j.isdigit():              
                r = x[x.find(j):]
                CC= x[:x.find(j)]
                break

I dont think, that this is an elegant way to solve this kind of task in python.我不认为这是在 python 中解决此类任务的一种优雅方式。 Can you please help me?你能帮我么?

As Seb said, regex!正如 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)

you could also do this in a one liner with regex:您也可以使用正则表达式在单行中执行此操作:

import re
s = 'R150C123'

r,c = list(map(int,re.findall('\d+',s)))

the re.findall function creates a list of all the numbers embedded in the string the map(int,...) function converts each matched number to a int finally list returns the ints as a list, allowing r&c to be defined in one assignment re.findall function 创建嵌入在字符串中的所有数字的列表 map(int,...) function 将每个匹配的数字转换为 int 最后列表将整数作为列表返回,允许在一个赋值中定义 r&c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM