s = "Alice"
a = 30
h = 165.5
print("Name: {}, Age: {}, Height: {}".format(s, a, h))
# Name: Alice, Age: 30, Height: 165.5
s = "Alice"
a = 30
h = 165.5
print("Name: {0}, Age: {1}, Height: {2}".format(s, a, h))
# Name: Alice, Age: 30, Height: 165.5
print("Height: {2}, Name: {0}, Age: {1}".format(s, a, h))
# Height: 165.5, Name: Alice, Age: 30
중괄호 안에 변수명을 사용하여 값을 참조할 수도 있습니다.
print("Name: {name}, Age: {age}, Height: {height}".format(name="Alice", age=30, height=165.5))
# Name: Alice, Age: 30, Height: 165.5
format 메서드를 사용하여 실수형 데이터를 포맷팅할 때 소수점 이하 자릿수를 지정할 수 있습니다.
{:.nf}: 소수점 이하 n자리까지 출력
{:.mf}: 전체 m자리 중 소수점 이하 n자리까지 출력
pi = 3.141592653589793
# 소수점 이하 2자리까지 출력
print("Value of Pi: {:.2f}".format(pi)) # Value of Pi: 3.14
# 소수점 이하 5자리까지 출력
print("Value of Pi: {:.5f}".format(pi)) # Value of Pi: 3.14159
# 전체 8자리 중 소수점 이하 3자리까지 출력
print("Value of Pi: {:8.3f}".format(pi)) # Value of Pi: 3.142
# 전체 10자리 중 소수점 이하 4자리까지 출력
print("Value of Pi: {:10.4f}".format(pi)) # Value of Pi: 3.1416