Python의 문자열 형식

완료됨

텍스트를 변환하고 일치 및 검색과 같은 기본 작업을 수행하는 것 외에도 정보를 표시할 때 텍스트의 형식을 지정하는 것은 중요합니다. Python으로 텍스트 정보를 표시하는 가장 간단한 방법은 print() 함수를 사용하는 것입니다. 변수 및 기타 데이터 구조의 정보를 print()가 사용할 수 있는 문자열로 가져오는 것이 중요합니다.

이 단원에서는 Python을 사용하여 텍스트에 변수 값을 포함하는 몇 가지 유효한 방법을 알아봅니다.

백분율 기호(%) 형식 지정

문자열의 변수에 대한 자리 표시자는 %s입니다. 문자열 뒤에 다른 % 문자와 변수 이름을 사용합니다. 다음 예제에서는 % 문자를 사용하여 서식을 지정하는 방법을 보여 줍니다.

mass_percentage = "1/6"
print("On the Moon, you would weigh about %s of your weight on Earth." % mass_percentage)

출력: On the Moon, you would weigh about 1/6 of your weight on Earth.

여러 값을 사용하면 전달되는 변수를 괄호로 묶어야 하므로 구문이 변경됩니다.

print("""Both sides of the %s get the same amount of sunlight, but only one side is seen from %s because the %s rotates around its own axis when it orbits %s.""" % ("Moon", "Earth", "Moon", "Earth"))

출력: Both sides of the Moon get the same amount of sunlight, but only one side is seen from Earth because the Moon rotates around its own axis when it orbits Earth.

이 메서드는 여전히 문자열의 형식을 지정하는 유효한 방법이지만, 여러 변수를 처리할 때 코드에서 오류가 발생하여 명확성이 감소할 수 있습니다. 이 단원에 설명된 다른 두 가지 형식 옵션 중 하나가 이러한 용도에 더 적합합니다.

format() 메서드

.format() 메서드는 중괄호({})를 문자열 내 자리 표시자로 사용하고 텍스트를 바꾸기 위해 변수 할당을 사용합니다.

mass_percentage = "1/6"
print("On the Moon, you would weigh about {} of your weight on Earth.".format(mass_percentage))

출력: On the Moon, you would weigh about 1/6 of your weight on Earth.

반복되는 변수를 여러 번 할당할 필요가 없으므로 할당해야 하는 변수가 더 적기 때문에 덜 자세합니다.

mass_percentage = "1/6"
print("""You are lighter on the {0}, because on the {0} you would weigh about {1} of your weight on Earth.""".format("Moon", mass_percentage))

출력: You are lighter on the Moon, because on the Moon you would weigh about 1/6 of your weight on Earth.

빈 중괄호 대신 숫자를 사용하여 대체합니다. {0}.format()에 대한 첫 번째(0의 인덱스) 인수를 사용하는 것을 의미하며, 이 경우에는 Moon입니다. 단순 반복의 경우 {0}이 잘 작동하지만 가독성이 떨어집니다. 가독성을 개선하려면 .format()에서 키워드 인수를 사용한 다음 중괄호 내에서 동일한 인수를 참조하세요.

mass_percentage = "1/6"
print("""You are lighter on the {moon}, because on the {moon} you would weigh about {mass} of your weight on Earth.""".format(moon="Moon", mass=mass_percentage))

출력: You are lighter on the Moon, because on the Moon you would weigh about 1/6 of your weight on Earth.

f-문자열 정보

Python 버전 3.6부터 f-문자열을 사용할 수 있습니다. 이러한 문자열은 템플릿처럼 보이고 코드의 변수 이름을 사용합니다. 이전 예제에서 f-문자열을 사용하면 다음과 같이 표시됩니다.

print(f"On the Moon, you would weigh about {mass_percentage} of your weight on Earth.")

출력: On the Moon, you would weigh about 1/6 of your weight on Earth.

변수는 중괄호 안으로 들어가며 문자열은 반드시 f 접두사를 사용해야 합니다.

f-문자열은 다른 형식 지정 옵션보다 덜 자세하며 중괄호 내에 식을 사용할 수 있습니다. 이러한 식은 함수 또는 직접 작업일 수 있습니다. 예를 들어 1/6 값을 소수점 이하 한 자리의 백분율로 나타내려면 직접 round() 함수를 사용할 수 있습니다.

print(round(100/6, 1))

출력: 16.7

f-문자열을 사용하면 변수에 값을 미리 할당할 필요가 없습니다.

print(f"On the Moon, you would weigh about {round(100/6, 1)}% of your weight on Earth.")

출력: On the Moon, you would weigh about 16.7% of your weight on Earth.

식을 사용하면 함수 호출이 필요하지 않습니다. 모든 문자열 메서드도 유효합니다. 예를 들어 제목을 만들기 위해 특정 대/소문자를 문자열에 적용할 수 있습니다.

subject = "interesting facts about the moon"
heading = f"{subject.title()}"
print(heading)

출력: Interesting Facts About The Moon