Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Capitalize a word using string.format()

Is it possible to capitalize a word using string formatting? For example,

"{user} did such and such.".format(user="foobar")

should return "Foobar did such and such."

Note that I'm well aware of .capitalize(); however, here's a (very simplified version of) code I'm using:

printme = random.choice(["On {date}, {user} did la-dee-dah. ",
                         "{user} did la-dee-dah on {date}. "
                         ])

output = printme.format(user=x,date=y)

As you can see, just defining user as x.capitalize() in the .format() doesn't work, since then it would also be applied (incorrectly) to the first scenario. And since I can't predict fate, there's no way of knowing which random.choice would be selected in advance. What can I do?

Addt'l note: Just doing output = random.choice(['xyz'.format(),'lmn'.format()]) (in other words, formatting each string individually, and then using .capitalize() for the ones that need it) isn't a viable option, since printme is actually choosing from ~40+ strings.

like image 872
tehsockz Avatar asked Jul 25 '13 02:07

tehsockz


People also ask

How do you capitalize words in a string in python?

Use title() to capitalize the first letter of each word in a string in python. Python Str class provides a member function title() which makes each word title cased in string. It means, it converts the first character of each word to upper case and all remaining characters of word to lower case.

What does capitalize () do in python?

The capitalize() method returns a string where the first character is upper case, and the rest is lower case.

Why we are use string capitalize () function?

The capitalize() method produces a string in which the first letter is capitalized and all other characters are lowercased. It makes no changes to the original string.

How do you auto capitalize in python?

The first letter of a string can be capitalized using the capitalize() function. This method returns a string with the first letter capitalized. If you are looking to capitalize the first letter of the entire string the title() function should be used.


4 Answers

As said @IgnacioVazquez-Abrams, create a subclass of string.Formatter allow you to extend/change the format string processing.

In your case, you have to overload the method convert_field

from string import Formatter
class ExtendedFormatter(Formatter):
    """An extended format string formatter

    Formatter with extended conversion symbol
    """
    def convert_field(self, value, conversion):
        """ Extend conversion symbol
        Following additional symbol has been added
        * l: convert to string and low case
        * u: convert to string and up case

        default are:
        * s: convert with str()
        * r: convert with repr()
        * a: convert with ascii()
        """

        if conversion == "u":
            return str(value).upper()
        elif conversion == "l":
            return str(value).lower()
        # Do the default conversion or raise error if no matching conversion found
        return super(ExtendedFormatter, self).convert_field(value, conversion)

# Test this code

myformatter = ExtendedFormatter()

template_str = "normal:{test}, upcase:{test!u}, lowcase:{test!l}"


output = myformatter.format(template_str, test="DiDaDoDu")
print(output)
like image 128
Tradjincal Avatar answered Oct 04 '22 22:10

Tradjincal


You can pass extra values and just not use them, like this lightweight option

printme = random.choice(["On {date}, {user} did la-dee-dah. ",
                         "{User} did la-dee-dah on {date}. "
                         ])

output = printme.format(user=x, date=y, User=x.capitalize())

The best choice probably depends whether you are doing this enough to need your own fullblown Formatter.

like image 42
John La Rooy Avatar answered Oct 04 '22 22:10

John La Rooy


You can create your own subclass of string.Formatter which will allow you to recognize a custom conversion that you can use to recase your strings.

myformatter.format('{user!u} did la-dee-dah on {date}, and {pronoun!l} liked it. ',
                      user=x, date=y, pronoun=z)
like image 42
Ignacio Vazquez-Abrams Avatar answered Oct 05 '22 00:10

Ignacio Vazquez-Abrams


In python 3.6+ you can use fstrings now. https://realpython.com/python-f-strings/

>>> txt = 'aBcD'
>>> f'{txt.upper()}'
'ABCD'
like image 26
David Parks Avatar answered Oct 05 '22 00:10

David Parks