0

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

programmerwiz32
  • 529
  • 1
  • 5
  • 20
  • Possible duplicate of [Capitalize the first letter after a punctuation](https://stackoverflow.com/questions/28639677/capitalize-the-first-letter-after-a-punctuation) – Jim G. Oct 22 '19 at 17:04
  • @JimG. should I delete question, that question answer me – programmerwiz32 Oct 22 '19 at 17:06
  • [title](https://python-reference.readthedocs.io/en/latest/docs/str/title.html) returns the string in Title Case. – DoesData Oct 22 '19 at 17:11

3 Answers3

1

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)
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
0

try this:

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

0

Basically what @Milad Barazandeh did but another way to do it

  • answer = "-".join([i[0].upper() + i[1:] for i in x.split("-")])
Waqar Bin Kalim
  • 321
  • 1
  • 7