MINERVA/Python 2021. 9. 5. 05:19
반응형

최근 프로젝트를 완료하면서, 개인적으로 다시 한번 파이썬(Python)에 대한 정리 필요성을 느끼게 되어 해당내용을 하나씩 기록하고자 합니다.

 

프로그래밍 언어를 공부시 개인적으로 제일 먼저 친해져야 하는 명령어가 출력문이다. 그 이유는 당연히 백문이 불여일견이 듯이, 백문이 불여일타의 첫시작이 출력문이기 때문이다.

 

# 문자열(string) 출력
print('Maing M&F')

# 문자열 포매팅(string formatting): 문자열의 원하는 위치에 변수값을 출력하는 것을 의미함
# 1) % 사용(서식문자): 정수(%d), 문자열(%s), 실수(%f), 문자(%%)...
str_sample1 = 'Hello %s' % 'Python'
print(str_sample1)

str_sample2 = 'My age: %d' % 18
print(str_sample2)

number = 1004
str_sample2 = 'My happy nummber : %d' % number

gifts=['bag','money','travel']
for gitf in gifts:
print('My gift is %s' % gitf)

# 인자가 두개 이상인경우: ()를 사용
str_sample3 = 'my name is %s and age is %d' % ('M&F',18)
print(str_sample3)

## 단점: formatter에 대응되는 데이터 타입을 정확히 알아야 하고,
## 코드가 길어지면 가독성이 떨어짐

# 2) str.format 사용(Python 3이상 부터 지원)
str_sample4 = 'Python version {}'.format(3)
print(str_sample4)

str_sample5 = 'My name: {}'.format('wonwoo')
print(str_sample5)

# multiple arguments
str_sample6 = 'My name is {0} and my age is {1}'.format('wonwoo',18)
print(str_sample6)

## 단점: 긴 문자열 처리 및 여러인자 일때 너무 문자열 길이가 길어지는 느낌!

# 3) f-string(Python 3.6이상 부터 지원)
name = 'wonwoo'
str_sample7 = f'My name is {name}'
print(str_sample7)

age = 18
str_sample8 = f'My name is {name} and age is {age}'
print(str_sample8)
## 정리: f-string이 가장 직관적이다. 사용하기 쉽다. 또한 속도 면에서도 가장빠르다.

 

반응형
posted by choiwonwoo
: