-1

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:

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

in python i do it like this

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?

because my way in python takes a to much time to execute.

another example for another String format is: Str="%[A-Z]%d", for example Str= ABCD1293

i want to save 2 values, the first one is an Array or a String and the second one is the numbers

in C i do it like this:

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

in Python like this:

        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. Can you please help me?

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 1
    Regular expressions are the way to go. Check out [this page](https://docs.python.org/3/library/re.html#simulating-scanf) from the standard library. – Seb Nov 13 '19 at 01:01
  • Does this answer your question? [How to extract numbers from a string in Python?](https://stackoverflow.com/questions/4289331/how-to-extract-numbers-from-a-string-in-python) – AMC Nov 13 '19 at 01:05
  • @AlexanderCécile this answers the first part of my question, i dont know how the answer for the second part should look like. – user10010048 Nov 13 '19 at 07:20
  • @user10010048 what is the second part? I’m not sure I understand which is which. – AMC Nov 15 '19 at 03:02

2 Answers2

0

As Seb said, regex!

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)
AMC
  • 2,642
  • 7
  • 13
  • 35
0

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

Derek Eden
  • 4,403
  • 3
  • 18
  • 31