Is it more Pythonic to use String Formatting over String Concatenation in Python 3?

前端 未结 3 1237
星月不相逢
星月不相逢 2020-12-18 14:29

So I\'m programming a text game in Python 3.4 that requires the use of the print() function very often to display variables to the user.

<
3条回答
  •  醉话见心
    2020-12-18 14:48

    It depends on the quantity and type of objects you're combining, as well as the kind of output you want.

    >>> d = '20160105'
    >>> t = '013640'
    >>> d+t
    '20160105013640'
    >>> '{}{}'.format(d, t)
    '20160105013640'
    >>> hundreds = 2
    >>> fifties = 1
    >>> twenties = 1
    >>> tens = 1
    >>> fives = 1
    >>> ones = 1
    >>> quarters = 2
    >>> dimes = 1
    >>> nickels = 1
    >>> pennies = 1
    >>> 'I have ' + str(hundreds) + ' hundreds, ' + str(fifties) + ' fifties, ' + str(twenties) + ' twenties, ' + str(tens) + ' tens, ' + str(fives) + ' fives, ' + str(ones) + ' ones, ' + str(quarters) + ' quarters, ' + str(dimes) + ' dimes, ' + str(nickels) + ' nickels, and ' + str(pennies) + ' pennies.'
    'I have 2 hundreds, 1 fifties, 1 twenties, 1 tens, 1 fives, 1 ones, 2 quarters, 1 dimes, 1 nickels, and 1 pennies.'
    >>> 'I have {} hundreds, {} fifties, {} twenties, {} tens, {} fives, {} ones, {} quarters, {} dimes, {} nickels, and {} pennies.'.format(hundreds, fifties, twenties, tens, fives, ones, quarters, dimes, nickels, pennies)
    'I have 2 hundreds, 1 fifties, 1 twenties, 1 tens, 1 fives, 1 ones, 2 quarters, 1 dimes, 1 nickels, and 1 pennies.'
    >>> f'I have {hundreds} hundreds, {fifties} fifties, {twenties} twenties, {tens} tens, {fives} fives, {ones} ones, {quarters} quarters, {dimes} dimes, {nickels} nickels, and {pennies} pennies.'
    'I have 2 hundreds, 1 fifties, 1 twenties, 1 tens, 1 fives, 1 ones, 2 quarters, 1 dimes, 1 nickels, and 1 pennies.'
    

    It is much easier to create without error a large format string than it is to do a lot of concatenation, too. Add in the fact that format strings can handle actual formatting, like alignment or rounding, and you'll soon leave concatenation for only the simplest cases, as shown above.

提交回复
热议问题