programmerwiz32
programmerwiz32

Reputation: 559

capitalizing the first letter in a text after split

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

Answers (3)

Waqar Bin Kalim
Waqar Bin Kalim

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

gen_Eric
gen_Eric

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

Milad Barazandeh
Milad Barazandeh

Reputation: 331

try this:

"-".join([i.capitalize() for i in x.split("-")])

Upvotes: 0

Related Questions