简体   繁体   中英

capitalize first letter of each line using regex

I am trying to make the first letter of every line an upper case

I am using the following regular expression

ModCon = re.sub('^[a-z]{1}', lambda x: x.upper(), ModCon)

nothing happens when I run the program.

The ^ anchor only matches the very start of your input string. If you want it to match after each newline, you need to give it the re.M or re.MULTILINE flag too:

ModCon = re.sub('^[a-z]', lambda x: x.group().upper(), ModCon, flags=re.M)

I removed the {1} part; it is implicit, without a repetition indicator the character set only matches one character.

The replacement function is passed a Match object , so you need to pull out the matched string by calling the .group() method.

The variable x in the lambda function is not of type string, but it is a <type '_sre.SRE_Match'>. In order to get the matching string, you need to call x.group() .

Thus (also using the hints in the other answers), the following script works fine:

import re
ModCon= "what is your favorite color?\nred"
ModCon = re.sub('^[a-z]', lambda x: x.group().upper(), ModCon, flags=re.M)
print (ModCon)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM