본문 바로가기

Python

Python [format] 스트링 안에 변수 값 넣고 출력

<함수 선언>

def say_hello(name, age):

  return "hellp {} you are {} year".format(name, age) <= 예전 방식 (1번)

  return f"hello {name} you are {age} years old" <= over python 3.6 (최신방식) (2번)

 

<1번 해설>

- 문자열 안에 변수 입력 부분을 {} 로 감싼다.

- 문자열 끝에 .format(변수) 를 첨부하여 format을 사용한다.

 

<2번 해설

- 위 처럼 문장 앞에 f(format) 선언 후 스트링 나열 한다.

- 그리고 arg 부분에 { } 로 감싸준다.

*2번 사용하는 것이 가장 빠르고 편하다.

 

hello = say_hello(age=22, name="kim") <- keyword argument 호출

print(hello) => hellp kim you are 22 year        - 1번

print(hello) => hello kim you are 22 years old  - 2번

 

 

<format 안에 산술 연산도 가능>

 

a = 2

b = 3

test = f"sum: {a + b}"

print(test) => sum: 5

 

'Python' 카테고리의 다른 글

Python [논리 연산자 and, or, not]  (0) 2019.11.24
Python if - elif - else  (0) 2019.11.24
Python [function] arg 위치 지정 호출  (0) 2019.11.24
Python [function] return , void 차이  (0) 2019.11.24
Python [function] argugment use  (0) 2019.11.24