Home > database >  regex sub() to capture first character of a string - Validating my script
regex sub() to capture first character of a string - Validating my script

Time:07-03

import re
def emphasise(txt):
    t = re.compile(r"\b(\w)")
    res = t.sub(r"\1".upper(),txt)      
    return res

res = emphasise("hello world")
print(res)

I am expecting "Hello World" but for some reason I am getting "hello world"

CodePudding user response:

use this in function:

 t.sub(lambda x: x.group().upper(), txt)

CodePudding user response:

Python's string has a title() method that capitalizes the words of the string.

def emphasise(txt):
    return txt.title()

res = emphasise("hello world")
print(res)  # Hello World

CodePudding user response:

You can use a lambda function to cast to uppercase initial characters:

import re
def emphasise(txt):
    return re.compile(r"\b(\w)").sub(lambda x: x.group().upper(), txt)    

res = emphasise("hello world")
print(res)

Hello World

  • Related