문자열 서식 지정#

소개#

파이썬에서 텍스트와 숫자를 포맷하는 권장 방법은 f-string을 사용하는 것입니다. f-string을 사용하면 변수, 표현식 및 함수 호출을 {} 안에 직접 포함할 수 있습니다.

f-문자열을 생성하려면 문자열 앞에 f 을 추가하고 변수, 표현식 또는 함수 호출을 {} 안에 배치합니다.

x = 1
y = 5

# Display the variables using an f-string
controller.screen.print(f"Position: ({x}, {y})")

# Display a calculation with an f-string
controller.screen.print(f"Sum: {5 + 3}")

# Display the robot's battery capacity with an f-string
controller.screen.print(f"Battery: {controller.get_battery_level()}%")

f-strings – 변수와 표현식을 텍스트에 직접 삽입합니다.

  • f”{value}” – 문자열 내의 변수, 표현식 또는 함수 호출을 표시합니다.

f-string에서 숫자 서식 지정 - 숫자 값의 표시 방식을 제어합니다.

  • :.xf – 표시할 소수 자릿수를 설정합니다.

  • round – 숫자를 지정된 소수 자릿수로 반올림합니다.

  • :, – 천 단위 구분 기호로 쉼표를 추가합니다.

  • :.x% – 소수를 x자리의 소수점 백분율로 변환합니다.

  • :#x – 숫자를 16진수로 포맷합니다.

  • :b – 숫자를 이진수로 포맷합니다.

문자열 조합 – 텍스트와 값을 결합합니다.

  • f”{value}” – 문자열과 변수를 단일 표현식으로 결합합니다.

  • + 연산자 – 선택적 유형 변환을 사용하여 문자열을 수동으로 연결합니다.

문자열 메서드 – 텍스트의 대소문자를 변경합니다.

  • upper – 모든 문자를 대문자로 변환합니다.

  • lower – 모든 문자를 소문자로 변환합니다.

부분 문자열 검사 – 텍스트의 존재 여부 또는 위치를 확인합니다.

  • in – 문자열에 단어가 존재하는지 확인합니다.

  • startswith – 문자열이 주어진 값으로 시작하는지 확인합니다.

  • endswith끝남 – 문자열이 주어진 값으로 끝나는지 확인합니다.

이스케이프 시퀀스 – 특수 문자를 사용하여 출력 형식을 지정합니다.

  • \n – 줄 바꿈(새 줄)을 추가합니다.

  • \t – 항목 사이에 탭 간격을 추가합니다.

f-string에서 숫자 형식 지정#

f-string은 다음과 같은 형식 지정자를 사용하여 소수점 자릿수, 반올림, 천 단위 구분 기호 등을 정밀하게 제어할 수 있도록 합니다.

Fixed Decimal Places#

.xf 숫자가 표시되는 소수점 자릿수를 제어합니다.

Usage:
.xf

매개변수

설명

x

표시할 소수점 자릿수입니다.

# Display pi with 2 decimal places
pi = 3.1415926535
controller.screen.print(f"Pi: {pi:.2f}")

# Output: Pi: 3.14

Rounding Numbers#

round f-문자열 외부 또는 {} 내부에 있는 숫자를 반올림합니다.

Usage:
round(number, x)

매개변수

설명

number

반올림할 숫자입니다.

x

반올림할 소수점 자릿수입니다.

# Display a value rounded to only 2 decimal places
value = 5.6789
controller.screen.print(f"{round(value, 2)}")

# Output: 5.68

Thousands Separator#

, 큰 숫자를 더 읽기 쉽게 하기 위해 천 단위 구분 기호로 쉼표를 삽입합니다.

Usage:
,

매개변수

설명

이 형식 지정자에는 매개변수가 없습니다.

# Display a large number separated with commas
number = 1234567
controller.screen.print(f"{number:,}")

# Output: 1,234,567

Percentage#

.x% 소수 값을 백분율로 표시합니다.

Usage:
.x%

매개변수

설명

x

표시할 소수점 자릿수입니다.

# Display a converted decimal to a percentage
value = 0.875

controller.screen.print(f"{value:.1%}")

# Output: 87.5%

Hexadecimal#

.#x 숫자를 16진수로 변환합니다.

Usage:
.#x

매개변수

설명

이 형식 지정자에는 매개변수가 없습니다.

# Convert 255 to hexadecimal
number = 255

controller.screen.print(f"{number:#x}")

# Output: 0xff

Binary#

b 숫자를 이진수(2진법)로 변환합니다.

Usage:
b

매개변수

설명

이 형식 지정자에는 매개변수가 없습니다.

# Convert 3 to binary
controller.screen.print(f"Binary: {3:b}")

# Output: Binary: 11

문자열 결합#

문자열을 결합(또는 연결)하는 방법에는 두 가지가 있습니다.

Using f-strings#

f-string을 사용하면 변수를 {} 안에 직접 삽입할 수 있습니다.

# Display an answer based on the given emotion
emotion = "good"

controller.screen.print(f"I'm {emotion}, you?")

+ Operator#

+ 연산자를 사용하여 문자열을 수동으로 결합할 수 있습니다.

참고: 문자열이 아닌 값은 먼저 str() str() 사용하여 문자열로 변환해야 합니다.

# Display the x and y values
x = 10
y = 20

controller.screen.print("X: " + str(x) + ", Y: " + str(y))

문자열 메서드#

파이썬은 문자열을 수정하고 검사하는 내장 메서드를 제공합니다.

upper#

upper 문자열의 모든 문자를 대문자로 변환합니다.

Usage:
upper()

매개변수

설명

이 메서드에는 매개변수가 없습니다.

# Display a message in uppercase
message = "vexcode"

controller.screen.print(message.upper())

# Output: VEXCODE

lower#

lower 문자열의 모든 문자를 소문자로 변환합니다.

Usage:
lower()

매개변수

설명

이 메서드에는 매개변수가 없습니다.

# Display a message in lowercase
message = "VEXCODE"

controller.screen.print(message.lower())

# Output: vexcode

부분 문자열 확인#

in#

in 은 문자열에 부분 문자열(단어 또는 텍스트 조각)이 존재하는지 여부를 나타내는 부울 값을 반환하는 키워드입니다.

  • True – 해당 단어가 문자열에 존재합니다.

  • False – 해당 단어가 문자열에 존재하지 않습니다.

# Display a message if "Hey" is in the string
message = "Hey everyone!"

if "Hey" in message:
    controller.screen.print("Hello!")

startswith#

startswith 은 문자열이 주어진 값으로 시작하는지 여부를 나타내는 부울 값을 반환합니다.

  • True – 해당 단어가 문자열의 시작 부분입니다.

  • False – 해당 단어가 문자열의 시작 부분이 아닙니다.

Usage:
startswith(substring)

매개변수

설명

substring

문자열의 시작 부분에서 확인할 부분 문자열입니다.

# Display a message if the string starts with "AIR"
message = "AIR Drone"

if message.startswith("AIR"):
    controller.screen.print("AIR first!")

endswith#

endswith 값을 반환합니다.

  • True – 해당 단어가 문자열의 끝입니다.

  • False – 해당 단어가 문자열의 끝에 있지 않습니다.

Usage:
endswith(substring)

매개변수

설명

substring

문자열 끝에서 확인할 부분 문자열입니다.

# Display a message if the string ends with "Drone"
message = "AIR Drone"

if message.endswith("Drone"):
    controller.screen.print("Drone last!")

탈출 시퀀스#

이스케이프 시퀀스는 텍스트 출력을 서식화하기 위해 문자열 내에서 사용되는 특수 문자입니다. 이는 Console에서만 사용할 수 있습니다.

New Line#

\n 인쇄 시 텍스트를 새 줄로 이동합니다.

# Display text on two lines
print("First line\nSecond line")

Tab Spacing#

\t 는 단어나 숫자 사이에 탭 공백을 삽입합니다.

# Display the quantity of barrels
quantity = 2
print("IDs:\t", quantity)