Reputation: 559
Is there an easy way to capitalize the first letter of each word after "-" in a string and leave the rest of string intact?
x="hi there-hello world from Python - stackoverflow"
expected output is
x="Hi there-Hello world from Python - Stackoverflow"
what I tried is :
"-".join([i.title() for i in x.split("-")]) #this capitalize the first letter in each word; what I want is only the first word after split
Note: "-" isn't always surrounded by spaces
Upvotes: 0
Views: 60
Reputation: 321
Basically what @Milad Barazandeh did but another way to do it
answer = "-".join([i[0].upper() + i[1:] for i in x.split("-")])
Upvotes: 0
Reputation: 227270
You can do this with a regular expression:
import re
x = "hi there-hello world from Python - stackoverflow"
y = re.sub(r'(^|-\s*)(\w)', lambda m: m.group(1) + m.group(2).upper(), x)
print(y)
Upvotes: 1
Reputation: 331
try this:
"-".join([i.capitalize() for i in x.split("-")])
Upvotes: 0