Reputation: 4229
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
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
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:
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
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