Search code examples
pythontitle-case

Python: Is there a one line script to title case strings except for strings that start with a digit?


The title() method works great, but I have a situation where there are strings that start with both words and numbers and I only want to titlecase the words in the string that do not begin with numbers.

The number of numbers can be variable, and there are not always numbers. Here is an example of each case.

"this is sparta".title() # This Is Sparta

"3rd sparta this is".title() # 3Rd Sparta This Is

"4545numbers start here".title() # "4545Numbers Start Here

I would like these to instead all be changed to:

"This Is Sparta"

"3rd Sparta This Is"

"4545numbers Start Here"

I am using a program that does not allow imports and I need to do this in one line. The only library I can use is re.

My preference would be to use a list comprehension to do this if possible.


Solution

  • Here's a simple list comprehension:

    ' '.join([word.capitalize() for word in your_string.split(' ')])
    

    If you want to split on punctuation and other whitespace you'd probably have to use some sort of re function.