Chapter 02. 자료형
1. 자료형과 문자열
자료(Data) : 프로그램이 처리(Processing)할 수 있는 모든것들
자료형(Data Type) : 문자열(String), 숫자(Number), 불(Boolean)
자료형 확인 : 함수 type()로 확인 가능합니다.
1
2
3
4
|
print(type(“こんばんは”)) # string
print(type(123)) # number
print(type(True)) # boolean
print(type(1)) # number? boolean??
|
cs |
<class ‘str’>
<class ‘int’>
<class ‘bool’>
<class ‘int’>
숫자는 int (number)
python3는 int와 float은 있지만
long, double은 없었다.
문자열(String)
1
2
3
4
|
print(“こんばんは”) # Double Quotes
print(‘こんばんは’) # Single Quotes
print(“へようこそ’Python'”) # Single in Double
print(‘”こんばんは”, 彼は言った.’) # Double in Single
|
cs |
따옴표 안에 따옴표를 넣을 수 있다. 같은 따옴표는 적용안됩니다.
こんばんは
こんばんは
へようこそ’Python’
“こんばんは”, 彼は言った.
1
|
print(“\”I want to escape!\””) # use \(backslash)
|
cs |
같은 따옴표를 사용하면 \(백슬래쉬)를 사용합니다.
“I want to escape!”
Escape Character(이스캐이프 문자) :
\(백슬래쉬,열슬래쉬) 와 같이 조합해서 사용하는 문자
ex)\”,\’\t, \n, \\
문자열 연산자
문자열 연결 연산자(+)
문자열 반복 연산자(*)
문자 선택 연산자(언덱싱, indexing)
1
2
3
4
5
|
print(“I python”[0])
print(“I python”[2])
print(“I python”[7])
print(“I python”[13])
print(“I python”[14])
|
cs |
1
2
3
4
5
6
7
8
|
Traceback (most recent call last) :
File “C:users\home\desktop\prog\python\week\indexing.py, line s, in <module>
I
I
P
‘
print(“I python“[14])
IndexError : string index out of range
|
cs |
마지막에 \0이 들어가지 않는다.
ch [12] : ‘
ch [13] :
ch [14] : ♀
C는 마지막 (13)에 ‘\0 이 들어간다.
1
2
3
4
5
|
# 거꾸로 출력 가능
print(“I python.”[–1])
print(“I python.”[–3])
print(“I python.”[–7])
print(“I python.”[–14])
|
cs |
‘
O
P
I
[Finished in 0.138s]
거꾸로 출력가능하군요
문자열 범위 선택 연산자(Slicing)
1
2
3
|
print(“I i python.”[:1])
print(“I i python.”[2:6])
print(“I i python.”[7:])
|
cs |
I
i
python.
[Finished in 0.107s]
IndexError(index out range) : 리스트, 문자열의 수를 넘는 범위를 사용한 경우.
4장 예외예서 다시 배움.
문자열의 길이: 함수 len() 사용
1
2
|
print(len(“who are you?”))
print(len(“I’m sinawi.”))
|
cs |
12
11
[Finished in 0.121s]
길이를 반환해줍니다.
2. 숫자
정수 나누기 연산자 “//”: 소수점 이하의 자릿수는 버리는 연산자
제곱 연산자 “**”:
3. 변수와 입력(p.74~91)
변수: 값을 저장할 때 사용하는 식별자
복합대입연산자
사용자 입력 함수: input() – string(문자열) 으로 저장
문자열을 숫자로 바꾸는 함수: int(), float()
숫자를 문자열로 바꾸는 함수: str()
4. 숫자와 문자열의 다양한 기능(p92~105)
format()함수: 문자열로 변환해주는 함수,
중괄호{}의 갯수와 format안에 매개변수의 갯수가 같아야됨.
ex)”{}”.format(123) -> “123”
“{}만원”.format(5000) -> “5000만원”
“{} {} {}”. format(1,”문자열”, True) -> “1 문자열 True”
– 정수 출력의 다양한 형태
“{:d}”.format(52) : 기본
“{:5d}”.format(52): 특정칸 출력
“{:05d}”.format(52): 빈칸을 0으로 채움
“{:+5d}”.format(52),
“{:+5d}”.format(-52):양수,음수 (기호를 뒤로 밀기)
“{:=+5d}”.format(52),
“{:=+5d}”.format(-52):양수,음수 (기호를 앞으로 밀기)
“{: d}”.format(52),
“{: d}”.format(-52):양수,음수 (기호부분 공백)
-부동소수점출력의 다양한 형태
“{:f}”.format(52.273)
-의미없는 소숫점 제거 {:g}
-대소문자 바꾸기 upper() lower()
-문자열 양옆의 공백 제거하기: strip(), lstrip() rstrip()
– 문자열의 구성 파악하기: is*()
isalnum, isalpha,isidentifier,isdecimal,isdigit,isspace,islower,isupper
-문자열 찾기: find()(왼쪽부터) rfind()(오른쪽부터)
-문자열과 in 연산자 -> True or False
-문자열 자르기: split() 괄호안을 기준으로 자름.
ex) a=”10 20 30 40 50″.split(” “
)>>> a= [’10’, ’20’, ’30’, ’40’, ’50’] -> 리스트