문자열 서식 지정#
소개#
Python의 .format() 메서드는 변수, 표현식 또는 값을 포함하는 문자열을 만드는 데 사용됩니다. 이 메서드는 문자열의 중괄호 자리 표시자 {} .format() 내부에 제공된 값으로 바꿉니다.
def main():
x = 1
y = 5
# Display the variables using .format()
brain.print("Position: ({}, {})".format(x, y))
# VR threads — Do not delete
vr_thread(main)
def main():
# Display a calculation using .format()
brain.print("Sum: {}".format(5 + 3))
# VR threads — Do not delete
vr_thread(main)
def main():
# Display the detected brightness using .format()
brain.print("Brightness: {}%".format(front_eye.brightness(PERCENT)))
# VR threads — Do not delete
vr_thread(main)
숫자 서식 지정( .format - 문자열에 값 및 표현식 삽입
:.xf– 표시할 소수 자릿수를 설정합니다.round– 숫자를 지정된 소수 자릿수로 반올림합니다.:,– 천 단위 구분 기호로 쉼표를 추가합니다.:.x%– 소수를 x자리의 소수점 백분율로 변환합니다.:#x– 숫자를 16진수로 포맷합니다.:b– 숫자를 이진수로 포맷합니다.
문자열 결합 – 텍스트와 값을 결합합니다.
.format()– 문자열과 변수를 단일 표현식으로 결합합니다.+ operator– 선택적 유형 변환을 사용하여 문자열을 수동으로 연결합니다.
문자열 메서드 – 텍스트의 대소문자를 변경합니다.
부분 문자열 확인 – 텍스트의 존재 여부 또는 위치를 확인합니다.
in– 문자열에 단어가 존재하는지 확인합니다.startswith()– 문자열이 주어진 값으로 시작하는지 확인합니다.endswith()– 문자열이 주어진 값으로 끝나는지 확인합니다.
이스케이프 시퀀스 – 특수 문자를 사용하여 출력 형식을 지정합니다.
숫자 서식 지정 ( .format#
.format 소수점 자릿수, 반올림 및 기타 서식 스타일을 포함하여 숫자가 표시되는 방식을 제어하는 데 사용할 수 있습니다.
Fixed Decimal Places#
.xf 숫자가 표시되는 소수점 자릿수를 제어합니다.
Usage:
.xf
매개변수 |
설명 |
|---|---|
|
표시할 소수점 자릿수입니다. |
def main():
# Display pi with 2 decimal places
pi = 3.1415926535
brain.print("Pi: {:.2f}".format(pi))
# Output: Pi: 3.14
# VR threads — Do not delete
vr_thread(main)
Rounding Numbers#
round 서식을 지정하기 전에 숫자를 지정된 소수점 자릿수로 반올림합니다.
Usage:
round(number, x)
매개변수 |
설명 |
|---|---|
|
반올림할 숫자입니다. |
|
반올림할 소수점 자릿수입니다. |
def main():
# Display a value rounded to only 2 decimal places
value = 5.6789
brain.print("Rounded: {}".format(round(value, 2)))
# Output: Rounded: 5.68
# VR threads — Do not delete
vr_thread(main)
Thousands Separator#
:, 큰 숫자를 더 읽기 쉽게 하기 위해 천 단위 구분 기호로 쉼표를 삽입합니다.
Usage:
:,
매개변수 |
설명 |
|---|---|
이 형식 지정자에는 매개변수가 없습니다. |
def main():
# Display a large number separated with commas
number = 1234567
brain.print("Formatted: ")
brain.new_line()
brain.print("{:,}".format(number))
# Output: Formatted: 1,234,567
# VR threads — Do not delete
vr_thread(main)
Percentage#
:.x% 소수 값을 100으로 곱하고 퍼센트 기호를 추가하여 백분율로 표시합니다.
Usage:
:.x%
매개변수 |
설명 |
|---|---|
|
표시할 소수점 자릿수입니다. |
def main():
# Display a converted decimal to a percentage
value = 0.875
brain.print("Score: {:.1%}".format(value))
# Output: Score: 87.5%
# VR threads — Do not delete
vr_thread(main)
Hexadecimal#
:#x 숫자를 16진수로 변환합니다.
Usage:
:#x
매개변수 |
설명 |
|---|---|
이 형식 지정자에는 매개변수가 없습니다. |
def main():
# Convert 255 to hexadecimal
number = 255
brain.print("Hex: {:#x}".format(number))
# Output: Hex: 0xff
# VR threads — Do not delete
vr_thread(main)
Binary#
:b 숫자를 이진수(2진법)로 변환합니다.
Usage:
:b
매개변수 |
설명 |
|---|---|
이 형식 지정자에는 매개변수가 없습니다. |
def main():
# Convert 3 to binary
brain.print("Binary: {:b}".format(3))
# Output: Binary: 11
# VR threads — Do not delete
vr_thread(main)
문자열 결합#
문자열을 결합(또는 연결)하는 방법에는 두 가지가 있습니다.
Using .format#
{} 사용하여 값을 문자열에 직접 삽입합니다.
def main():
# Display an answer based on the given emotion
emotion = "good"
brain.print("I'm {}, you?".format(emotion))
# VR threads — Do not delete
vr_thread(main)
+ Operator#
+ 사용하여 여러 부분을 결합합니다.
참고: 문자열이 아닌 값은 먼저 str() str() 사용하여 문자열로 변환해야 합니다.
def main():
# Display the x and y values
x = 10
y = 20
brain.print("X: " + str(x) + ", Y: " + str(y))
# VR threads — Do not delete
vr_thread(main)
문자열 메서드#
파이썬은 문자열을 수정하고 검사하는 내장 메서드를 제공합니다.
upper#
upper 문자열의 모든 문자를 대문자로 변환합니다.
Usage:
upper()
매개변수 |
설명 |
|---|---|
이 메서드에는 매개변수가 없습니다. |
def main():
message = "vexcode"
brain.print(message.upper()) # Output: VEXCODE
# VR threads — Do not delete
vr_thread(main)
lower#
lower 문자열의 모든 문자를 소문자로 변환합니다.
Usage:
lower()
매개변수 |
설명 |
|---|---|
이 메서드에는 매개변수가 없습니다. |
def main():
message = "VEXCODE"
brain.print(message.lower()) # Output: vexcode
# VR threads — Do not delete
vr_thread(main)
부분 문자열 확인#
in#
in 은 문자열에 부분 문자열(단어 또는 텍스트 조각)이 존재하는지 여부를 나타내는 부울 값을 반환하는 키워드입니다.
True– 해당 단어가 문자열에 존재합니다.False– 해당 단어가 문자열에 존재하지 않습니다.
def main():
message = "Hey everyone!"
if "Hey" in message:
brain.print("Hello!")
# VR threads — Do not delete
vr_thread(main)
startswith#
startswith 은 문자열이 주어진 값으로 시작하는지 여부를 나타내는 부울 값을 반환합니다.
True– 해당 단어가 문자열의 시작 부분입니다.False– 해당 단어가 문자열의 시작 부분이 아닙니다.
Usage:
startswith(substring)
매개변수 |
설명 |
|---|---|
|
문자열의 시작 부분에서 확인할 부분 문자열입니다. |
def main():
message = "VR Robot"
if message.startswith("VR"):
brain.print("VR first!")
# VR threads — Do not delete
vr_thread(main)
endswith#
endswith 값을 반환합니다.
True– 해당 단어가 문자열의 끝입니다.False– 해당 단어가 문자열의 끝에 있지 않습니다.
Usage:
endswith(substring)
매개변수 |
설명 |
|---|---|
|
문자열 끝에서 확인할 부분 문자열입니다. |
def main():
message = "VR Robot"
if message.endswith("Robot"):
brain.print("Robot last!")
# VR threads — Do not delete
vr_thread(main)
탈출 시퀀스#
이스케이프 시퀀스는 문자열 내에서 텍스트 출력 형식을 지정하는 데 사용되는 특수 문자입니다. 콘솔에서만 사용할 수 있습니다.
New Line#
\n 인쇄 시 텍스트를 새 줄로 이동합니다.
def main():
# Display text on two lines
brain.print("First line\nSecond line")
# VR threads — Do not delete
vr_thread(main)
Tab Spacing#
\t 는 단어나 숫자 사이에 탭 공백을 삽입합니다.
def main():
# Display the quantity of barrels
quantity = 2
brain.print("Boxes:\t", quantity)
# VR threads — Do not delete
vr_thread(main)