· Programming

Python String Formatting

Set variable user to string “Alice”. Set variable salary to float “200.25”.

user = 'Alice'
salary = 200.25

1. C Style String Formatting

In this type of formatting the position of variable inside a string is marked by %X where X is the data type of the operator. The character followed by % indicates the data type. %s -> string %f -> float %d -> Integer (digit)

Since the variable user is a string we specify %s.

print('Hello, %s' %user)
Hello, Alice

Since variable salary is a float we specified its position with %f.

print('Your salary is %f' %salary)

Your salary is 200.250000 Floats can be converted to int or str by using %d or %f

print('Your salary is %d' %salary)
print('Your salary is %s' %salary)

Your salary is 200
Your salary is 200.25

Note: If wrong data type is specified python will automatically convert it. This code will raise error as str can’t be converted to int directly.

print('Hello, %d' %user)


---

TypeError Traceback (most recent call last)
<ipython-input-21-6c63a23f0284> in <module>
----> 1 print('Hello, %d' %'0')

TypeError: %d format: a number is required, not str

Multiple Variables in a sentence

print('%s\'s salary is %d.' %(user, salary))

Rounding off floats %.Nf where N is the number of decimal places required.

print('%s\'s salary is %f' %(user, salary))
print('%s\'s salary is %.1f' %(user, salary))

Alice's salary is 200.250000
Alice's salary is 200.2

Topics

  • Python
  • String Formatting