name = input() # steve
age = int(input()) # 23
string = name + "is" + str(age) + "years old."
print(string) # steve is 23 years old.
보통 문자열을 더하는(이어주는) 코드를 짤 때 '+' 연산자를 사용한다.
이럴 때 문제점은 전부 string으로 형반환해줘야 한다.
그리고 각 문자열에 " "를 사용해 문자열임을 명시해줘야 한다는 점이다.
name = input() # steve
age = int(input()) # 23
# Example 1
string = f"{name} is {age} years old."
print(string) # steve is 23 years old.
# Example 2
string = f"He is {age-3} years old in 2020."
print(string) # He is 20 years old in 2020.
Python 3.6 이후 버전부터는 이를 f-string으로 해소할 수 있다.
Example 1처럼 f" " 안에 문자열을 작성하고, { } 안에 매개변수를 적어주면 그에 대응하는 값을 출력한다.
Example 2처럼 { } 안에 계산식을 입력하는 것도 가능하다.
# string : s / int : d / float : f
# left : null or < / center : ^ / right : >
text = "Never say never"
print(f"{text:20s}") # Never say never
print(f"{text:^20s}") # Never say never
print(f"{text:>20s}") # Never say never
number = 123456789
print(f"{number:<20d}") # 123456789
print(f"{number:^20d}") # 123456789
print(f"{number:>20d}") # 123456789
pi = 3.141592
print(f"{pi:<15f}") # 3.141592
print(f"{pi:^15f}") # 3.141592
print(f"{pi:>15f}") # 3.141592
이때 서식 지정자를 사용하여 글자를 정렬하는 것도 가능하다.
{ } 안에 colon(:)을 기준으로 왼쪽에는 변수를, 오른쪽에는 '정렬기호 + 자릿수 + 서식 지정자' 알파벳으로 적어준다.
< ^ > 는 각각 왼쪽, 가운데, 오른쪽 정렬을 하라는 정렬 기호이다.
이때 왼쪽 정렬은 < 대신 아무것도 쓰지 않아도 된다. (text 예시)
그리고 변수형에 따라 s(문자열), d(정수), f(실수)를 맞춰 작성해 주어야 한다.
number = 3.141592
print(f"number is {number:.2f}") # number is 3.14
number = 1
print(f"number is {number:.2f}") # number is 1.00
소수점 자리를 지정해줄 수도 있다.
{ } 안에 colon(:)을 기준으로 왼쪽에는 숫자를, 오른쪽에는 ".자릿수f" 형태로 적어준다.
위의 코드처럼 number:.2f로 적게 되면 number 변수를 소수점 둘째 자리까지 출력하라는 의미이다.
정수여도 지정해준 자리까지 패딩하여 출력한다.
고민을 시작한 문제 출처 : https://www.youtube.com/shorts/X4E4aQriiwI
'Computer Science > 파이썬(Python)' 카테고리의 다른 글
Python Round(반올림) 설명 (0) | 2023.06.24 |
---|---|
Python lambda (0) | 2023.04.03 |
Python zip (0) | 2023.03.30 |
Python if comprehension (0) | 2023.03.28 |
Python enumerate (0) | 2023.03.28 |