user3422637
user3422637

Reputation: 4229

Python: Convert entire string to lowercase except for substrings in quotes

I have a python string received from user input.

Let's say the user input is something like this:

 I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'

If this string is stored in a variable called input_string, and I apply .lower() on it, it would convert the whole thing into lowercase.

input_string = input_string.lower()

Result:

i am enrolled in a course, 'mphil' since 2014. i love this 'so much'

Here's what I desire the lowercase to do: Convert everything, except what's in quotes, into lowercase.

i am enrolled in a course, 'MPhil' since 2014. i love this 'SO MuCH'

Upvotes: 1

Views: 2248

Answers (3)

Jordan Keane
Jordan Keane

Reputation: 1

You can use this regex pattern to solve this problem for the example string and strings containing any number of words between the single quotes.

import re
pat = re.compile(r"(^|' )([\w .,]+)($| ')") 

input_string_1 = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'"
input_string_2 = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO SO MuCH'"

output_string_1 = pat.sub(lambda match: match.group().lower(), input_string_1)
output_string_2 = pat.sub(lambda match: match.group().lower(), input_string_2)

print(input_string_1)
print(output_string_1)
print(input_string_2)
print(output_string_2)

Upvotes: 0

Robert
Robert

Reputation: 259

This is my first stack overflow answer. It's defintely not the most elegant code but it works for your question. You can break this answer down as follows:

  1. Split string to a list
  2. Create two sub-lists
  3. Convert desired sub-list to lower
  4. Concatenate sub-lists
  5. Print with a join method on the list

Here is the code:

string = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'"  
l = string.split()    #split string to list
lower_l = l[0:11]       
unchanged_l = l[11:]  #create sub-lists with split at 11th element
lower_l = [item.lower() for item in lower_l]    #convert to lower
l = lower_l + unchanged_l    #concatenate
print ' '.join(l)     #print joined list delimited by space

Upvotes: 0

alecxe
alecxe

Reputation: 473873

We can use the combination of negative lookahead, lookbehind, applying word boundaries and using a replacement function:

>>> s = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'"
>>> re.sub(r"\b(?<!')(\w+)(?!')\b", lambda match: match.group(1).lower(), s)
"i am enrolled in a course, 'MPhil' since 2014. i love this 'SO MuCH'"

Upvotes: 4

Related Questions