1

Here is what I am trying to achieve: I want to replace

void some_function(int,  int *, float);

with

void some_function(int a, int *b, float c);

So far, I have tried to replace "," with chr(97+i) as I loop through the string.

text = len("void some_function(int,  int *, float);")
i = 0
for j in range(0, length)
    if text[j] == ",":
       rep = " " + chr(97+i) + " .,"
       text = text.replace("," rep)
       i = i + 1
       j = 0 # resetting the index, but this time I want to find the next occurrence of "," which I am not sure

But this is not doing the job. Please let me know if there is a better way of doing this.

4
  • 2
    You are trying to refractor C code with python? Commented Jun 7, 2012 at 17:23
  • I am new to python, not sure how to go about this! :( Commented Jun 7, 2012 at 17:26
  • 1
    If you are trying to refactor generic code, it's a very non-trivial task. Think about cases where the function arguments span more than one line. Cases with 0 or 1 argument (no commas). How about void other_function(void) where you don't want a variable name? Commented Jun 7, 2012 at 17:45
  • If you are refactoring C code, I think you are better off doing this with a good code text editor... Commented Jun 7, 2012 at 17:55

3 Answers 3

1
import re

i = 96
def replace(matches):
    global i
    i += 1
    return " " + chr(i) + matches.group(0)

re.sub(',|\)', replace, "void some_function(int,  int *, float);")
Sign up to request clarification or add additional context in comments.

3 Comments

Nice answer, but it should be noted this will only work once, since i is global. After that you'll get d,e,f,g...until it explodes.
I don't know C, but I was wondering, isn't it a problem that there's a space between * and b in the result?
@BrtH: Nope: int* b, int *b, int * b, and even int*b are valid
1
text = "void some_function(int,  int *, float);".replace(',', '%s,') % (' a', 'b')

Comments

0

The original idea does not work, since the last parameter is not followed by a ',' but by a ')'.

import re
import string

def fix(text):
    n = len(re.findall('[,(]', text))
    return re.sub('([,)])', ' %s\\1', text) % tuple(string.letters[:n])

1 Comment

Correctly answers the OP's very specific case, but still fails for things like fix('joefunc()') and fix('joefunc(void)'). Not a dig on the answer, just a note for the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.