Skip to content

Latest commit

 

History

History
86 lines (65 loc) · 1.99 KB

File metadata and controls

86 lines (65 loc) · 1.99 KB

String formatting or interpolation operator

C-style (printf-style)

String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values (Python standard library).

Examples:

num = [1,2,3]
for i in num:
  print("The number is: %d" % (i))

# The number is: 1
# The number is: 2
# The number is: 3
num = [1,2,3]
for i in num:
  print("%d divided by %d is %f" % (i,i+1,i/(i+1)))
  
# 1 divided by 2 is 0.500000
# 2 divided by 3 is 0.666667
# 3 divided by 4 is 0.750000
import os

file = [1,2,3]
for i in file:
  os.system("echo File number %s is available" % (i))

# File number 1 is available
# File number 2 is available
# File number 3 is available

The following is a list of some important string formatting specifications:

Format Meaning
%s a string
%d an integer
%f a decimal with 6 decimals
%e scientific notation (with e)
%g compact decimal or scientific notation (with e)
%.xy format y with x decimals, eg. .12f

F-string style

This method is avalable for Python 3.6 and higher. Review here to learn more.

num = [1,2,3]
for i in num:
  print(f"The number is: {i}")

# The number is: 1
# The number is: 2
# The number is: 3
num = [1,2,3]
for i in num:
  print(f"{i} divided by {i+1} is {i/(i+1)}")

# 1 divided by 2 is 0.500000
# 2 divided by 3 is 0.666667
# 3 divided by 4 is 0.750000
import os

file = [1,2,3]
for i in file:
  os.system(f"echo File number {i} is available")

# File number 1 is available
# File number 2 is available
# File number 3 is available