How to replace each occurrence of _a or -a in A?

Hello guys,

I’m doing an exercise in Python. I have to replace in a text all the occurrences of _(char) or -(char) or *(char) by char in capital letters(CHAR).

For example, I have a text like get_element_by_name or set-name and I have to replace these texts by getElementByName or setName

I don’t know how to do that

There are a number of ways to do this. I’m not sure what you have learnt at this point.

You can use regex:

"""
Regex explaination
([_\-\*]) matches _, - or *. \ is and escape for the special regex characters. This is group 1
?<= Is positive lookahead, so it will look for _, - or * before  the ([a-z]) part. 
([a-z]) means match any character that is from a to z lower case (only 1 character). This is group 2
"""
import re

def matchToUpper(match):
    newValue = match.group()
    newValue = newValue.replace(match.group(1), "")
    newValue = newValue.replace(match.group(2), match.group(2).upper())
    return newValue
    
pattern = "([_\-\*])(?<=[_\-\*])([a-z])"

example1 = "get_element_by_name"
formattedExample1 = re.sub(pattern, matchToUpper, example1)
print(formattedExample1)

example2 = "set*name"
formattedExample2 = re.sub(pattern, matchToUpper, example2)
print(formattedExample2)

Regex probably isn’t the expected answer though. What have you learnt at this point? Loops? Splitting strings and arrays? Because it can be done with both of them too.

Edit: Oops, originally did the code in JavaScript not Python.

Edit2: Just noticed I miss read what the output should be. You haven’t said what to do with double __/–/** so this will not do anything special with them and will leave the extra one and still capitalise the following character.

1 Like
str = "get___element-by*name**"

newstr = ""
i = 0
upcase = False
while i < len(str):
    if str[i] in ("_-*"):
        upcase = True
    elif upcase:
        newstr += str[i].upper()
        upcase = False
    else:
        newstr +=str[i]
    i +=1

print(newstr)

Somebody may have a better solution :thinking:

Thanks for the reply. In the function matchToUpper, the parameter match is another function from the package re. why put that in parameter? I don’t know a lot about regex

There is a match in re, you are right but that isn’t the parameter. The match parameter is what is passed into matchToUpper internally by re.sub and will be each part of the example string that matches the regex.

You could change match in matchToUpper to have whatever name you want if it makes it more clear, lazy and bad naming on my part.

Just a quick regex (shirt for regular expression) overview. It is a search pattern that is used against strings to find matching parts, it can then be used to also replace those parts (as here). Regular expression has its own syntax but the basics aren’t too hard to grasp and it can be a pretty powerful tool when you get good with it (like using it to validate dates, including leap years).