Python: Capitalize a word using string.format()

前端 未结 4 2072
萌比男神i
萌比男神i 2021-02-01 06:39

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

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

should return \

相关标签:
4条回答
  • 2021-02-01 06:49

    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)
    
    0 讨论(0)
  • 2021-02-01 07:02

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

    >>> txt = 'aBcD'
    >>> f'{txt.upper()}'
    'ABCD'
    
    0 讨论(0)
  • 2021-02-01 07:04

    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.

    0 讨论(0)
  • 2021-02-01 07:10

    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)
    
    0 讨论(0)
提交回复
热议问题