Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making letters uppercase using re.sub in python?

Tags:

python

regex

In many programming languages, the following

find foo([a-z]+)bar and replace with GOO\U\1GAR

will result in the entire match being made uppercase. I can't seem to find the equivalent in python; does it exist?

like image 844
Jordan Reiter Avatar asked Jan 19 '12 22:01

Jordan Reiter


People also ask

How do you use re sub in Python?

If you want to replace a string that matches a regular expression (regex) instead of perfect match, use the sub() of the re module. In re. sub() , specify a regex pattern in the first argument, a new string in the second, and a string to be processed in the third.

What does re Ignorecase do in Python?

re. IGNORECASE : This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z] will match lowercase letters, too. Generally, It's passed as an optional argument to re. compile() .

How do you change lowercase to uppercase in Python?

In Python, lower() is a built-in method used for string handling. The lower() method returns the lowercased string from the given string. It converts all uppercase characters to lowercase. If no uppercase characters exist, it returns the original string.


2 Answers

You can pass a function to re.sub() that will allow you to do this, here is an example:

 def upper_repl(match):      return 'GOO' + match.group(1).upper() + 'GAR' 

And an example of using it:

 >>> re.sub(r'foo([a-z]+)bar', upper_repl, 'foobazbar')  'GOOBAZGAR' 
like image 199
Andrew Clark Avatar answered Oct 08 '22 22:10

Andrew Clark


Do you mean something like this?

>>>x = "foo spam bar" >>>re.sub(r'foo ([a-z]+) bar', lambda match: r'foo {} bar'.format(match.group(1).upper()), x) 'foo SPAM bar' 

For reference, here's the docstring of re.sub (emphasis mine).

Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.

like image 28
wim Avatar answered Oct 08 '22 22:10

wim