Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 367
Startec Avatar asked Aug 28 '15 22:08

Startec


1 Answers

As it turns out, there's already a function that does this, string.capwords:

>>> import string
>>> string.capwords('1st foo bar bor1ng baz')
'1st Foo Bar Bor1ng Baz'
>>> string.capwords("3rd sparta this is")
'3rd Sparta This Is'

One thing to beware of: runs of whitespace will be collapsed into a single space, and leading and trailing whitespace will be removed. Notably, this means you'll lose line separators. You should split into lines first if you wish to preserve those.

Note that internally, it actually uses the capitalize method instead of title, but this appears to be what you want.

like image 56
jpmc26 Avatar answered Oct 25 '22 01:10

jpmc26