문자열 서식 지정#

소개#

Python의 .format() 메서드는 변수, 표현식 또는 값을 포함하는 문자열을 만드는 데 사용됩니다. 이 메서드는 문자열의 중괄호 자리 표시자 {} .format() 내부에 제공된 값으로 바꿉니다.

x = 1
y = 5

# Display the variables using .format()
print("Position: ({}, {})".format(x, y))

# Display a calculation using .format()
print("Sum: {}".format(5 + 3))

wait(1, SECONDS)
# Display the time using .format()
print("Time: {}".format(timer.time(SECONDS)))

숫자 서식 지정( .format - 문자열에 값 및 표현식 삽입

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

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

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

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

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

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

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

  • .format() – 문자열과 변수를 단일 표현식으로 결합합니다.

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

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

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

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

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

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

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

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

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

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

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

숫자 서식 지정 ( .format#

.format 소수점 자릿수, 반올림 및 기타 서식 스타일을 포함하여 숫자가 표시되는 방식을 제어하는 ​​데 사용할 수 있습니다.

Fixed Decimal Places#

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

Usage:
:.xf

매개변수

설명

x

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

# Display pi with 2 decimal places
pi = 3.1415926535
console.print("Pi: {:.2f}".format(pi))
# Output: Pi: 3.14

Rounding Numbers#

round 서식을 지정하기 전에 숫자를 지정된 소수점 자릿수로 반올림합니다.

Usage:
round(number, x)

매개변수

설명

number

반올림할 숫자입니다.

x

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

# Display a value rounded to only 2 decimal places
value = 5.6789
console.print("Rounded: {}".format(round(value, 2)))
# Output: Rounded: 5.68

Thousands Separator#

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

Usage:
:,

매개변수

설명

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

# Display a large number separated with commas
number = 1234567
print("Formatted: ")
print("{:,}".format(number))
# Output: Formatted: 1,234,567

Percentage#

:.x% 소수 값을 100으로 곱하고 퍼센트 기호를 추가하여 백분율로 표시합니다.

Usage:
:.x%

매개변수

설명

x

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

def main():
    # Display a converted decimal to a percentage
    value = 0.875
    console.print("Score: {:.1%}".format(value))
    # Output: Score: 87.5%

# Start threads — Do not delete
start_thread(main)

Hexadecimal#

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

Usage:
:#x

매개변수

설명

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

def main():
    # Convert 255 to hexadecimal
    number = 255
    console.print("Hex: {:#x}".format(number))
    # Output: Hex: 0xff

# Start threads — Do not delete
start_thread(main)

Binary#

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

Usage:
:b

매개변수

설명

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

def main():
    # Convert 3 to binary
    console.print("Binary: {:b}".format(3))
    # Output: Binary: 11

# Start threads — Do not delete
start_thread(main)

문자열 결합#

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

Using .format#

{} 사용하여 값을 문자열에 직접 삽입합니다.

def main():
    # Display an answer based on the given emotion
    emotion = "good"
    console.print("I'm {}, you?".format(emotion))

# Start threads — Do not delete
start_thread(main)

+ Operator#

+ 사용하여 여러 부분을 결합합니다.

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

def main():
    # Display the x and y values
    x = 10
    y = 20
    console.print("X: " + str(x) + ", Y: " + str(y))

# Start threads — Do not delete
start_thread(main)

문자열 메서드#

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

upper#

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

Usage:
upper()

매개변수

설명

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

def main():
    # Capitalize a string with .upper()
    message = "vexcode"
    console.print(message.upper())  # Output: VEXCODE

# Start threads — Do not delete
start_thread(main)

lower#

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

Usage:
lower()

매개변수

설명

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

def main():
    # Make a string lowercase with .lower()
    message = "VEXCODE"
    console.print(message.lower())  # Output: vexcode

# Start threads — Do not delete
start_thread(main)

부분 문자열 확인#

in#

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

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

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

def main():
    message = "Hey everyone!"
    if "Hey" in message:
        console.print("Hello!")

# Start threads — Do not delete
start_thread(main)

startswith#

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

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

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

Usage:
startswith(substring)

매개변수

설명

substring

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

def main():
    # Check for 'V5' at the start of a string
    message = "V5 Robot"

    if message.startswith("V5"):
        console.print("V5 first!")

# Start threads — Do not delete
start_thread(main)

endswith#

endswith 값을 반환합니다.

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

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

Usage:
endswith(substring)

매개변수

설명

substring

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

def main():
    # Check for `Robot` at the end of a string
    message = "V5 Robot"

    if message.endswith("Robot"):
        console.print("Robot last!")

# Start threads — Do not delete
start_thread(main)

탈출 시퀀스#

이스케이프 시퀀스는 문자열 내에서 텍스트 출력 형식을 지정하는 데 사용되는 특수 문자입니다.

New Line#

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

def main():
    # Display text on two lines
    console.print("First line\nSecond line")

# Start threads — Do not delete
start_thread(main)

Tab Spacing#

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

def main():
    # Display the quantity of disks
    quantity = 2
    console.print("Disks:\t", quantity)

# Start threads — Do not delete
start_thread(main)