본문 바로가기

BackEnd/Python

자료형 - 문자형

큰 따옴표로 양쪽 둘러싸기

 

"Hello World"

 

 

작은 따옴표로 양쪽 둘러싸기

 

'Hello World'

 

 

큰 따옴표 3개를 연속으로 써서 양쪽 둘러싸기

 

"""Hello World"""

 

 

작은 따옴표 3개를 연속으로 써서 양쪽 둘러싸기

 

'''Hello World'''

 

 

문자열 더해서 연결하기

 

head = "Hello"
tail = " World"

>>> head + tail = "Hello World"

 

 

문자열 곱하기

 

a = "python"
a * 2

>>> 'pythonpython'

 

 

인덱싱

 

a = "Life is too short, You need Python"
a[3] // 앞은 0부터 시작한다.

>>> 'e'

a[-0]
>>> L // 0과 -0은 똑같다.

a[-2] // 뒤는 1부터 시작한다.
>>> 'o'

 

 

슬라이싱 (0 <= x < 3)

 

a = "Life is too short, You need Python"
a[0:3]

>>> "Lif"

a[19:]
>>> "You need Python"

a[:]
>>> "Life is too short, You need Python"

a[19:-7]
>>> "You need"

 

 

포매팅

 

"I eat %d appels." % 3
>>> "I eat 3 appels."

"I eat %s appels." % "five"
>>> "I eat five appels."

"I eat %d appels. so I was sick for %s days." % (10, "three")
>>> "I eat 10 appels. so I was sick for three days."

%s == String
%c == Charactor
%d == Integer
%f == Floating-point
%o == 8진수
%x == 16진수
%% == 문자 '%' 자체

 

 

포맷 코드와 숫자

 

"%10s" % "hi"
>>> "        hi" // 공백(8자)으로 오른쪽 정렬

"%0.4f" % 3.42134234
>>> "3.4213" // 소수점 4번째 자리까지

"%10.4f" % 3.42134234
>>> "    3.4213" // 공백(4자) 삽입 후 소수점 4번째 자리까지

 

 

format 함수를 사용한 포매팅

 

"I eat {0} {1} appels." . format(3, "five")
>>> "I eat 3 five appels."

"I eat {number} appels. so I was sick for {day} days." . format(number=10, day=3)
>>> "I eat 10 appels. so I was sick for 3 days."

 

 

정렬

 

"{0:<10}" . format("hi")
>>> "hi        " // 왼쪽 정렬

"{0:>10}" . format("hi")
>>> "        hi" // 오른쪽 정렬

"{0:^10}" . format("hi")
>>> "     hi     " // 중앙 정렬

"{0:=^10}" . format("hi")
>>> "====hi====" // 공백 채우기

 

 

'BackEnd > Python' 카테고리의 다른 글

자료형 - 딕셔너리형  (0) 2020.06.18
자료형 - 튜플형  (0) 2020.06.18
자료형 - 리스트형  (0) 2020.06.16
자료형 - 숫자형  (0) 2020.06.04
파이썬(Python)이란?  (0) 2020.05.07