Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- insert
- ftp
- create table
- STF
- 28015
- ssh
- Jupyter
- nohup
- perfect
- STF_PortForwarding
- appium
- Materials
- postgres
- GoCD
- SWIFT
- Jupyter Notebook
- postgresql
- ubuntu
- centos
- nmap
- sshpass
- mysql
- openpyxl
- port forwarding
- appium server
- PYTHON
- nGrinder
- kitura
- 실행권한
- rethinkdb
Archives
- Today
- Total
don't stop believing
f-string 문자열에 변수 넣기 (3.6) 본문
Python을 사용하다보면 (다른 프로그래밍도 마찬가지지만) 문자열에 변수를 대입해 화면에 출력해야 할 때가 많습니다.
Python 3.6부터 f-string이 추가되었습니다.
어떻게 사용하는지 확인해 보겠습니다.
더 자세한 내용은 아래 링크에서 확인할 수 있습니다.
https://realpython.com/python-f-strings/
먼저 Old Style String formatting 입니다.
보통 2.7 이전에 많이 사용한 스타입니다.
123456789name = "tongchun" # type 'str'age = 42 # type 'int'height = 176.5 # type 'float'married = True # type 'bool'# Old Style String Formattingmessage = "My name is %s. Age is %d. Height is %0.1f. He is married (%r)" % (name, age, height, married)print(message)# My name is tongchun. Age is 42. Height is 176.5. He is married (True)
위에것 보다 진보된게 format String입니다.
string 타입에 .format() 함수를 추가해 사용합니다.
12345678910111213name = "tongchun" # type 'str'age = 42 # type 'int'height = 176.5 # type 'float'married = True # type 'bool'# Format Stringmessage = "My name is {}. Age is {}. Height is {}.He is married ({})".format(name, age,height, married)print(message)# My name is tongchun. Age is 42. Height is 176.5. He is married (True)message = "He is married ({m}), His name is {name} and age is {age}.".format(name=name, age=age, h=height, m=married)print(message)# He is married (True), His name is tongchun and age is 42.
formatting string에 대해서는 아래 링크에 자세히 설명되어 있습니다.
https://www.python-course.eu/python3_formatted_output.php
이번엔 3.6에서 추가된 새로운 f-string입니다.
문자열 앞에 f를 추가해 f-string인 것을 선언합니다. f는 소문자 대문자 관계없습니다.
12345678910111213141516name = "tongchun" # type 'str'age = 42 # type 'int'height = 176.5 # type 'float'married = True # type 'bool'# f-stringmessage = f"My name is {name}. Age is {age}. Height is {height}.He is married ({married})"print(message)# My name is tongchun. Age is 42. Height is 176.5. He is married (True)message2 = (f"He is married ({married})"f"His name is {name} and age is {age}.")print(message2)# He is married (True)His name is tongchun and age is 42.
Python 3.6 이상 버전을 사용한다면 f-string이 더 편할 것 같습니다.
'Python > Basic' 카테고리의 다른 글
blockchain 테스트에 사용한 python 함수 - getDateStrings (0) | 2018.12.17 |
---|---|
if condition 한 줄로 쓰기 (one-liner) (3) | 2018.12.09 |
Python 3.x 설치 (on CentOS7) (3) | 2018.10.15 |
파일 읽어서 다시 쓰기 (0) | 2018.03.05 |
Windows에 Python 설치하기 2 (0) | 2018.01.30 |