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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With