
함수
divmod
몫과 나머지를 한 번에 구한다.
>>> divmod(11, 4) (2, 3)
max
max(a,b)일 때 a와 b 중 큰 쪽 값을 반환한다.
>>> max(2, 6) 6 >>> max(-4,-8) -4 >>> max(2.4, 3.14) 3.14
min
min(a,b)일 때 a와 b 중 작은 쪽 값을 반환한다.
>>> min(2, 6) 2 >>> min(-4,-8) -8 >>> min(2.4, 3.14) 2.4
type
인수에 수치나 변수를 주면 그 데이터형을 반환 값으로 돌려준다.
>>> type(6) <class 'int'> >>> type(7.8) <class 'float'> >>> type(-4) <class 'int'> >>> type(-5.723) <class 'float'> >>> type(3.0) <class 'float'>
int
부동소수점형의 값 및 부울값, 문자열을 정수로 변환한다.
>>> int(2.6) 2 >>> int("-5") -5 >>> int(True) 1 >>> int(False) 0 >>> int("hello") Traceback (most recent call last): File "<pyshell#53>", line 1, in <module> int("hello") ValueError: invalid literal for int() with base 10: 'hello'
float
정수나 부울값, 문자열을 부동소수점으로 변환한다.
>>> float(3) 3.0 >>> float("-2.58") -2.58 >>> float(True) 1.0 >>> float(False) 0.0 >>> float("hello") Traceback (most recent call last): File "<pyshell#58>", line 1, in <module> float("hello") ValueError: could not convert string to float: 'hello’
str
수치나 부울값을 문자열로 변환한다.
>>> str(7) '7' >>> str(0) ‘0’ >>> str(0.0) '0.0' >>> str(True) 'True' >>> str(False) 'False’
bool
수치나 문자열을 부울값으로 변환한다.
0이나 0.0, 빈 문자열은 False가 되지만 그 외의 값은 전부 True가 된다.
>>> bool(3) True >>> bool(0) False >>> bool(-1.4) True >>> bool(0.0) False >>> bool(' ') True >>> bool('') False >>> bool('hello')
len
리스트나 튜플에 포함되는 요소 수를 반환한다.
>>> len([1,2,3,4,5]) 5 >>> len(("small","medium","large")) 3 >>> data=[[1,2],[3,4,5],[6,7,8,9]] >>> len(data) 3 >>> len(data[2]) 4
sorted
인수로 주어진 리스트나 튜플을 정렬해 그 복사본을 반환한다. 본래 리스트의 정렬 순서는 바뀌지 않는다.
>>> fruits=["banana", "apple","peach","orange"] >>> sorted(fruits) ['apple', 'banana', 'orange', 'peach'] >>> fruits ['banana', 'apple', 'peach', 'orange']
인수로 주어진 정보를 출력 영역인 콘솔에 표시한다.
여러 값을 표시하는 경우는 콤마 구분으로 지정한다.
다른 형의 데이터를 여러 개 표시하려면, 다음과 같이 서식이 있는 문자열을 사용해 새로운 문자열을 작성한다.
>>> print("hello") hello >>> print(3) 3 >>> print(False) False >>> print("Hi!","Python",3) Hi! Python 3
Method
append
리스트 맨 끝에 요소를 추가할 수 있다.
>>> weekdays=["Monday","Tuesday","Wednesday", "Thurrsday","Friday"] >>> weekdays.append("Saturday") >>> weekdays ['Monday', 'Tuesday', 'Wednesday', 'Thurrsday', 'Friday', 'Saturday']
insert
지정한 위치에 요소를 추가할 수 있다.
>>> animals=["horse","rabbit","lion","elephant","mouse"] >>> animals.insert(3,"Rhino") >>> animals ['horse', 'rabbit', 'lion', 'Rhino', 'elephant', 'mouse']
pop
리스트의 특정 요소를 삭제 후 반환한다.
>>> animals ['horse', 'rabbit', 'lion', 'Rhino', 'elephant', 'mouse'] >>> animals.pop(2) 'lion' >>> animals ['horse', 'rabbit', 'Rhino', 'elephant', 'mouse']
copy
자신과 같은 복제를 만들어 반환한다.
--copy 메서드를 사용하지 않았을 때-- >>> a=[1,2,3] >>> b=a >>> a[2]=9 >>> a [1, 2, 9] >>> b [1, 2, 9] --copy 메서드를 사용했을 때-- >>> a=[1,2,3] >>> b=a.copy() >>> a[2]=9 >>> a [1, 2, 9] >>> b [1, 2, 3]
index
단순하게 포함돼 있는지 아닌지가 아닌, 몇 번째에 저장돼 있는지 확인하고 싶을 때 사용.
>>> greets ('morning', 'afternoon', 'evening') >>> greets.index("afternoon") 1 >>> scores [92, 45, 87, 36, 72] >>> scores.index(36) 3 >>> scores.index(99) Traceback (most recent call last): File "<pyshell#131>", line 1, in <module> scores.index(99) ValueError: 99 is not in list
sort
본래 리스트를 그 자리에서 정렬한다. 반환 값은 없다.
>>> fruits ['banana', 'apple', 'peach', 'orange'] >>> fruits.sort() >>> fruits ['apple', 'banana', 'orange', 'peach']
format
데이터를 삽입하고 싶은 장소에 { }를 배치한다. 문자열에 대해서 format 메서드를 호출해 그 인수로 실제 데이터를 전달한다.
{ } 안에 번호를 기재함으로써 순서를 바꿀 수 있고, 이름을 붙여 지정할 수도 있다.
서식 문자열을 사용하면 자릿수를 지정하거나 오른쪽 정렬, 왼쪽 정렬시키거나 패딩을 주는 등 여러 가지 서식을 지정할 수 있다.
>>> "1={} 2={}".format("Hello","World") '1=Hello 2=World' >>> "value=({},{})".format(2,5) 'value=(2,5)' >>> "score={}".format(2.457) 'score=2.457’ >>> "value=({1},{0})".format(2,5) 'value=(5,2)’ >>> "value({latitude},{longitude})".format(latitude=35.6,longitude=139.6) 'value(35.6,139.6)‘
명령
del
리스트의 특정 요소를 삭제할 수 있다.
>>> animals ['horse', 'rabbit', 'lion', 'Rhino', 'elephant', 'mouse'] >>> del animals[2] >>> animals ['horse', 'rabbit', 'Rhino', 'elephant', 'mouse']
연산자
in
어떠한 값이 리스트나 튜플에 포함되었는지 확인한다.
>>> greets=("morning","afternoon","evening") >>> "noon" in greets False >>> "afternoon" in greets True >>> scores=[92,45,87,36,72] >>> 36 in scores True >>> 67 in scores False
%
본래 문자열 내에 ‘%s’나 ‘%d’ 등의 서식을 삽입해 둔다. 이 부분을 실제 데이터로 바꿔 놓는 방법이다. 문자열 뒤에 % 연산자를 배치하고, 그 뒤에 튜플 형식으로 실제 데이터를 배치한다.
%s→문자열
%d→10진수
%x→16진수
%f→10진 float
서식의 형과 실제 데이터는 일치시켜야 하며, 일치하지 않는 경우는 오류가 발생한다.
(현재는 format 메서드를 사용하는 방법이 주류이다.)
>>> "1=%s 2=%s" % ("Hello","World") '1=Hello 2=World' >>> "value=(%d, %d)" % (2, 5) 'value=(2, 5)' >>> "score=%f" % (2.457) 'score=2.457000' >>> "age=%d" %("hello") Traceback (most recent call last): File "<pyshell#147>", line 1, in <module> "age=%d" %("hello") TypeError: %d format: a number is required, not str
'Programming Language > Python' 카테고리의 다른 글
게임으로 배우는 파이썬 Part 1 Chapter 4 :PyGame (2) | 2021.12.24 |
---|---|
게임으로 배우는 파이썬 Part 1 Chapter 3 :제어문 (0) | 2021.12.16 |
백준 문제 풀때, python3과 pypy3의 차이 (0) | 2021.12.04 |
Python - deque objects (0) | 2021.12.01 |
파이썬 알아두면 좋은 표현 (0) | 2021.11.26 |