print()
함수print()
함수는 문자열을 콘솔에 출력하는 가장 기본적인 함수이다.
# 기본 출력
print("Hello, world!")
# 여러 값을 공백으로 구분하여 출력
name = "Alice"
age = 25
print("Name:", name, "Age:", age) # Name: Alice Age: 25
# abs(x) : 절대값 반환
print(abs(-30)) # 30
sep
매개변수sep
매개변수는 separation로 구분자 역할을 한다.
print('S','E','P', sep='@') # S@E@P
end
매개변수# 출력 끝에 추가 문자 삽입 (예: 줄바꿈 대신)
print("Hello", end=" ")
print("World") # Hello World
*
연산자*
연산자는 리스트, 리스트, 튜플, 문자열과 같은 시퀀스의 요소를 한 번에 출력한다.
my_list = [3, 2, 4, 1]
print(*my_list) # 3 2 4 1
print(my_list) # [3, 2, 4, 1]
my_string = "abcde"
print(*my_string) # a b c d e
print(my_string) # abcde
*
연산자를 붙여서 함수를 호출하면, 마치 여러 개의 인자를 넘긴 효과가 남.print()
함수에는 가변 길이의 인자를 넘길 수 있음. 기본적으로는 공백을 구분자로 사용.print(*sorted(my_list)) # 1 2 3 4
와 같이 응용해서 사용할 수 있음.format()
함수는 문자열을 포맷팅할 때 사용하는 파이썬의 강력한 도구이다. 다양한 방법으로 변수를 문자열에 삽입하거나, 수치 포맷을 지정하는 데 유용하다.
즉, format()
메서드는 문자열 안에 변수 값을 삽입할 때 사용한다.
string.format(value, ...)
name = "Alice"
age = 25
# 기본 사용
print("Name: {}, Age: {}".format(name, age)) # Name: Alice, Age: 25
# 인덱스를 사용한 사용
print("Name: {0}, Age: {1}".format(name, age)) # Name: Alice, Age: 25
# 키워드를 사용한 사용
print("Name: {name}, Age: {age}".format(name=name, age=age)) # Name: Alice, Age: 25
# 중괄호
print('Format example. {{}}, {}'.format('test')) # Format example. {}, test
{}
)는 자리표시자(placeholder)로, 그 자리에 format()
함수의 인자가 차례대로 들어감.◾️ 왼쪽 정렬 : <
◾️ 오른쪽 정렬 : >
◾️ 가운데 정렬 : ^
# 왼쪽 정렬
print('This is {:<10}|'.format('left')) # This is left |
print('This is {:-<10}|'.format('left')) # This is left------|
# 오른쪽 정렬
print('This is {:>10}|'.format('right')) # This is right|
# 가운데 정렬
print('This is {:^10}|'.format('center')) # This is center |
{:<10}
: 10자리 폭에 왼쪽 정렬.{:>10}
: 10자리 폭에 오른쪽 정렬.{:^10}
: 10자리 폭에 가운데 정렬.# 자리수 채우기 (패딩)
print('정수 3자리 : {0:03d}, {1:03d}'.format(12345, 23)) # 정수 3자리 : 12345, 023
# 소수점 자리 지정
print('아래 2자리 : {0:.2f}, 아래 5자리 : {1:0.5f}'.format(3.141592, 3.14)) # 아래 2자리 : 3.14, 아래 5자리 : 3.14000
{0:03d}
는 0번 째 인덱스에 숫자를 3자리로 맞추고, 앞의 빈 자리는 0으로 채우라는 의미.{:.2f}
는 소수점 아래 2자리까지 숫자를 표시하라는 의미.◾️ {:b}
: 2진수
◾️ {:o}
: 8진수
◾️ {:x}
: 16진수 (소문자)
◾️ {:X}
: 16진수 (대문자)
format()
을 사용하여 2진수, 8진수, 16진수로 변환된 문자열을 쉽게 출력할 수 있다.
# 10진수를 2진수, 8진수, 16진수로 변환하여 출력
number = 255
formatted_str = "Binary: {0:b}, Octal: {0:o}, Hexadecimal: {0:x}".format(number)
print(formatted_str)
# 출력: Binary: 11111111, Octal: 377, Hexadecimal: ff
◾️ {:,}
는 숫자를 천 단위 쉼표로 구분.
formatted_str = "The population is {:,}".format(1000000)
print(formatted_str)
# 출력: The population is 1,000,000
percentage = 0.85
formatted_str = "Success rate: {:.1%}".format(percentage)
print(formatted_str)
# 출력: Success rate: 85.0%
{:.1%}
는 소수점 한 자리까지 퍼센트(%
) 형식으로 표시◾️ %s
: 문자열
◾️ %d
: 정수
◾️ %f
: 실수
print("%s을 %d개 주세요."%("아이스크림", 10)) # 아이스크림을 10개 주세요.
f-strings
f-strings
은 파이썬 3.6 이상에서 사용할 수 있는 문자열 포매팅 방법으로, 문자열 앞에 f
를 붙여 사용한다.
# f-문자열 사용
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}") # Name: Alice, Age: 25
# 표현식도 삽입 가능
print(f"In 5 years, {name} will be {age + 5} years old.") # In 5 years, Alice will be 30 years old.
이스케이프 시퀀스 | 설명 |
---|---|
\' | 작은 따옴표 |
\\ | 백슬래시 |
\n | 줄바꿈 |
\r | 캐리지 리턴(ASCII Carriage Return, CR) |
\t | 탭 |
\b | 백스페이스 |
\f | 폼피드(ASCII Formfeed, FF) |
\ooo | 8진수 숫자를 지정하여 ASCII 코드의 문자 표현 |
\xhh | 16진수 숫자를 지정하여 ASCII 코드의 문자 표현 |
print("8진수: \110\145\154\154\157") # 8진수: Hello
print("16진수: \x48\x65\x6c\x6c\x6f") # 16진수: Hello
참고,
https://www.w3schools.com/python/gloss_python_escape_characters.asp