Python string formatting percent

Python string formatting with percent sign

but it is syntax error. What would be the proper way of doing this without indexing like the first example?

it’s arguable whether it’s more «pythonic» but str.format would allow you to use *args expansion since it’s a method call

3 Answers 3

str % .. accepts a tuple as a right-hand operand, so you can do the following:

>>> x = (1, 2) >>> y = 'hello' >>> '%d,%d,%s' % (x + (y,)) # Building a tuple of `(1, 2, 'hello')` '1,2,hello' 

Your try should work in Python 3, where Additional Unpacking Generalizations is supported, but not in Python 2.x:

Actuall the extended iterable unpacking does not allow that syntax (python3.4): >>> ‘%d,%d,%s’ % (*x, y) File «», line 1 SyntaxError: can use starred expression only as assignment target Maybe it’ll be allowed by python3.5’s Additional Unpacking Generalizations

>>> x = (5,7) >>> template = 'first: <>, second: <>' >>> template.format(*x) 'first: 5, second: 7' 

Update:

For completeness I am also including additional unpacking generalizations described by PEP 448. The extended syntax was introduced in Python 3.5, and the following is no longer a syntax error:

>>> x = (5, 7) >>> y = 42 >>> template = 'first: <>, second: <>, last: <>' >>> template.format(*x, y) # valid in Python3.5+ 'first: 5, second: 7, last: 42' 

In Python 3.4 and below, however, if you want to pass additional arguments after the unpacked tuple, you are probably best off to pass them as named arguments:

>>> x = (5, 7) >>> y = 42 >>> template = 'first: <>, second: <>, last: ' >>> template.format(*x, last=y) 'first: 5, second: 7, last: 42' 

This avoids the need to build a new tuple containing one extra element at the end.

Читайте также:  Использование памяти в java

Источник

Python String Interpolation with the Percent (%) Operator

There are a number of different ways to format strings in Python, one of which is done using the % operator, which is known as the string formatting (or interpolation) operator. In this article we’ll show you how to use this operator to construct strings with a template string and variables containing your data.

The % Operator

This way of working with text has been shipped with Python since the beginning, and it’s also known as C-style formatting, as it originates from the C programming language. Another description for it is simple positional formatting.

The % operator tells the Python interpreter to format a string using a given set of variables, enclosed in a tuple, following the operator. A very simple example of this is as follows:

'%s is smaller than %s' % ('one', 'two') 

The Python interpreter substitutes the first occurrence of %s in the string by the given string «one», and the second %s by the string «two». These %s strings are actually placeholders in our «template» string, and they indicate that strings will be placed there.

As a first example, below we demonstrate using the Python REPL how to print a string value and a float value:

>>> print("Mr. %s, the total is %.2f." % ("Jekyll", 15.53)) 'Mr. Jekyll, the total is 15.33.' 

Just like the %s is a placeholder for strings, %f is a placeholder for floating point numbers. The «.2» before the f is what indicates how many digits we want displayed after the decimal point.

These are just two simple examples of what is possible, and a lot more placeholder types are supported. Here is the full list of placeholder types in more detail:

%c

This placeholder represents a single character.

>>> print("The character after %c is %c." % ("B", "C")) The character after B is C. 

Providing more than a single character as the variable here will raise an exception.

%s

This placeholder uses string conversion via str() prior to formatting. So any value that can be converted to a string via str() can be used here.

>>> place = "New York" >>> print("Welcome to %s!" % place) Welcome to New York! 

Here we only have a single element to be used in our string formatting, and thus we’re not required to enclose the element in a tuple like the previous examples.

%i and %d

These placholders represent a signed decimal integer.

>>> year = 2019 >>> print("%i will be a perfect year." % year) 2019 will be a perfect year. 

Since this placeholder expects a decimal, it will be converted to one if a floating point value is provided instead.

%u

This placeholder represents an unsigned decimal integer.

%o

This placeholder represents an octal integer.

>>> number = 15 >>> print("%i in octal is %o" % (number, number)) 15 in octal is 17 
%x

Represents a hexadecimal integer using lowercase letters (a-f).

>>> number = 15 >>> print("%i in hex is %02x" % (number, number)) 15 in hex is 0f 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

By using the «02» prefix in our placeholder, we’re telling Python to print a two-character hex string.

%X

Represents a hexadecimal integer using uppercase letters (A-F).

>>> number = 15 >>> print("%i in hex is %04X" % (number, number)) 15 in hex is 000F 

And like the previous example, by using the «04» prefix in our placeholder, we’re telling Python to print a four-character hex string.

%e

Represents an exponential notation with a lowercase «e».

%E

Represents an exponential notation with an uppercase «e».

%f

Represents a floating point real number.

>>> price = 15.95 >>> print("the price is %.2f" % price) the price is 15.95 
%g

The shorter version of %f and %e .

%G

The shorter version of %f and %E .

The placeholders shown above allow you to format strings by specifying data types in your templates. However, these aren’t the only features of the interpolation operator. In the next subsection we’ll see how we can pad our strings with spaces using the % operator.

Aligning the Output

Up until now we’ve only shown how to format text strings by specifying simple placeholders. With the help of an additional numerical value, you can define the total space that shall be reserved on either side of a variable in the output string.

As an example the value of %10s reserves 10 characters, with the extra spacing on the left side of the placeholder, and a value of %-10s puts any extra space to the right of the placholder. The single padding character is a space, and cannot be changed.

>>> place = "London" >>> print ("%10s is not a place in France" % place) # Pad to the left London is not a place in France >>> print ("%-10s is not a place in France" % place) # Pad to the right London is not a place in France 

Dealing with numbers works in the same way:

>>> print ("The postcode is %10d." % 25000) # Padding on the left side The postcode is 25000. >>> print ("The postcode is %-10d." % 25000) # Padding on the right side The postcode is 25000 . 

Truncating strings and rounding numbers is the counterpart to padding. Have a look at Rounding Numbers in Python in order to learn more about the traps that are hiding here.

Conclusion

In this article we saw how the interpolation (aka formatting) operator is a powerful way to format strings, which allows you to specify data type, floating point precision, and even spacing/padding.

Источник

How to print a percentage value?

Given a float between 0 and 1, how to print it as a percentage? For example, 1/3 should print as 33% .

Percent means per hundred. If you have a simple ratio ( 1/3 in your case), you have a per unit value that have to multiply it by 100 to get a percent value. See the other answers for the difference between integer and float division.

FWIW, in Python 3.x print(str(float(1/3))+’%’) will print 0.3333333333333333% — still not exactly what you want, but at least it’s a bit closer. This is because division works differently in that version.

8 Answers 8

>>> f"" '33%' >>> "".format(1/3) '33%' >>> format(1/3, ".0%") '33%' 

Percentage. Multiplies the number by 100 and displays in fixed ( ‘f’ ) format, followed by a percent sign.

The .0 part of the format spec .0% indicates that you want zero digits of precision after the decimal point, because with f»» you would get the string ‘33.333333%’ .

It works with integers, floats, and decimals. See PEP 3101.

@TobiasKienzler, I do not know, if it’s more pythonic. At least it is something you stumble over while reading the code. I think with Python 3 and real division by default this irritation is gone.

Indeed. I wonder why Guido didn’t implement real division from the very start. Rounding 1/3 to 0 should be explicit after all.

In Python 2, I’d use 1.0 instead of float(1) or 1. . IMHO it’s less obtrusive than the former and not as subtle as the latter.

There is a way more convenient ‘percent’-formatting option for the .format() format method:

This is the best answer because it doesn’t require a multiplication by 100. Rather it takes advantage of the fact that format already knows how to print percentages!

This should be the accepted answer. This is much more Pythonic, using built-in capabilities to eliminate the meaningless implementation detail that a multiplication by 100 would be.

Just for the sake of completeness, since I noticed no one suggested this simple approach:

  • %.0f stands for «print a float with 0 decimal places«, so %.2f would print 33.33
  • %% prints a literal % . A bit cleaner than your original +’%’
  • 1.0 instead of 1 takes care of coercing the division to float, so no more 0.0

@martialdidit: I’m aware of that, that’s why my answer does not have parenthesis in 1/3 . Evaluation order is intentional: 100.0 * 1 / 3 => 100.0 / 3 => 0.33.

Beg your pardon, @RuggeroTurra? This is formatting, in the broad sense that it transforms an input to display as a string. Please note the OP never required the use of .format() , and % -formatting, also known as string interpolation in Python, is a perfectly valid alternative.

With % you are formatting a float to a string. Not a float to a percentage-string. The multiplication by 100 is done by hand, not by the %. I think the only correct solution which only uses formatting is with

Just to add Python 3 f-string solution

prob = 1.0/3.0 print(f"") # 33% print(f"") # 33.33% 

it should be like this instead: print(f»%»)

@MichalK No, it should not. When your number is a fraction then you need to use f»«, to auto-convert to percentage.

You are dividing integers then converting to float. Divide by floats instead.

To specify a percent conversion and precision.

>>> float(1) / float(3) [Out] 0.33333333333333331 >>> 1.0/3.0 [Out] 0.33333333333333331 >>> ''.format(1.0/3.0) # use string formatting to specify precision [Out] '33%' >>> ''.format(percent=1.0/3.0) [Out] '33.33%' 

Then you’d want to do this instead:

The .0 denotes them as floats and int() rounds them to integers afterwards again.

i know this is from 2011 but . int() does not round. e.g. int(1.9) != 2 . Rounding can be done like so — round(1.9,0) == 2

int() certainly does round down the number. My example does exactly what I meant it to do; cutting off the digits since that’s what the OP wanted.

Stockoverflow is great — a couple of year and still a response. Thank you. However, for the sake of completeness, I want to clarify. int() drops the digits. It does not round down. Rounding implies it does something with the digits. The end result is the same though; in that sense, I see your point. Also, the OP does not clarify what he/she wants to do with the digits has 33.333. does round to 33. Thank you for responding to my comment and have a great day!

Источник

Оцените статью