Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize specific letters in a string given certain rules

Tags:

python

string

I am massaging strings so that the 1st letter of the string and the first letter following either a dash or a slash needs to be capitalized.

So the following string:

test/string - this is a test string

Should look look like so:

Test/String - This is a test string

So in trying to solve this problem my 1st idea seems like a bad idea - iterate the string and check every character and using indexing etc. determine if a character follows a dash or slash, if it does set it to upper and write out to my new string.

def correct_sentence_case(test_phrase):

corrected_test_phrase = ''

firstLetter = True

for char in test_phrase:

    if firstLetter:

        corrected_test_phrase += char.upper()

        firstLetter = False

    #elif char == '/':
    else:

        corrected_test_phrase += char

This just seems VERY un-pythonic. What is a pythonic way to handle this?

Something along the lines of the following would be awesome but I can't pass in both a dash and a slash to the split:

corrected_test_phrase = ' - '.join(i.capitalize() for i in test_phrase.split(' - '))

Which I got from this SO:

Convert UPPERCASE string to sentence case in Python

Any help will be appreciated :)

like image 740
beginAgain Avatar asked Jan 21 '26 10:01

beginAgain


1 Answers

I was able to accomplish the desired transformation with a regular expression:

import re
capitalized = re.sub(
    '(^|[-/])\s*([A-Za-z])', lambda match: match[0].upper(), phrase)

The expression says "anywhere you match either the start of the string, ^, or a dash or slash followed by maybe some space and a word character, replace the word character with its uppercase."

demo

like image 89
wbadart Avatar answered Jan 23 '26 00:01

wbadart