유용한 Python 내장함수 (1)

idle-danie·2023년 1월 25일
2
post-thumbnail

Python 내장함수, 자료형, 정규표현식, 모듈...etc


문자열 공간 채우기 (zfill(), rjust())

  • zfill(): 특정 width만큼 0채우기 (단, 이미 width가 채워져 있다면 변화 X)
>>> a = "0b113"
>>> a[2:].zfill(5)
'00113'
  • rjust(): 0이아닌 특정 문자 지정 가능
>>> a[2:].rjust(5, "a")
'aa113'

특정 원소 인덱스 찾기 (index(), index())

  • index()
>>> a = ["Kim", "Lee"]
>>> a.index("Lee")
1

>>> a.index("Lim")
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    a.index("Lim")
ValueError: 'Lim' is not in list
  • find()
>>> a.find("Kim")
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    a.find("Kim")
AttributeError: 'list' object has no attribute 'find'

>>> b = "Kim"
>>> b.find("i")
1

>>> b.find("h")
-1

Binary 계산

  • int(): n진수 -> 10진수
>>> int("1111",2)
15
>>> int("1111",3)
40
  • bin(), 논리연산
>>> bin(20)
'0b10100'

>>> 39 | 22 # OR 연산
55
>>> 38 & 33 # AND 연산
32
>>> 39 ^ 32 # XOR 연산
7
>>> ~39 # NOT 연산
-40

순열, 조합

from itertools import permutations, combinations, product, combinations_with_replacement

data = ['A', 'B', "C"]

result = list(permutations(data, 2))
print(result) # 순열

result1 = list(combinations(data,2))
print(result1) # 조합

result2 = list(product(data, repeat=2))
print(result2) # 중복순열

result3 = list(combinations_with_replacement(data, 2))
print(result3) #중복조합

[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
[('A', 'B'), ('A', 'C'), ('B', 'C')]
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]

문자열에서 특정 문자 교체

  • replace()
>>> a
'hellohelloworld'
>>> a = a.replace("hello","stop")
>>> a
'stopstopworld'
>>> a = a.replace("stop", "",1)
>>> a
'stopworld'
>>> a = a.replace("stop", "hello")
>>> a
'helloworld'
>>> a.replace("hello","j").replace("w","k")
'jkorld'
>>> a = 'helloworld'
>>> a = a[:2].replace("he", "hello")
>>> a
'hello'

find(), join(), split()을 이용한 문자열 삽입

>>> myIntro = "{} is {} years old".format(myName, myAge)
>>> myIntro = "Daniel is 25 years old"
>>> idx = myIntro.find("25")
>>> idx
10
>>> myProfile = myIntro[:idx] + "good at soccer and " + myIntro[idx:]
>>> myProfile
'Daniel is good at soccer and 25 years old'
>>> stringList = myProfile.split()
>>> stringList.insert(5, "and polite ")
>>> myProfile = ' '.join(stringList)
>>> myProfile
'Daniel is good at soccer and polite  and 25 years old'

리스트 요소 삭제

  • del list[ ]
>>> a = [1,2,3,4,5]
>>> del a[1]
>>> a
[1, 3, 4, 5]
  • remove()
>>> b = [1,1,1,1,66,88,99]
>>> b.remove(1)
>>> b
[1, 1, 1, 66, 88, 99]
>>> for i in b:
	b.remove(3)
	print(b)

Traceback (most recent call last):
  File "<pyshell#129>", line 2, in <module>
    b.remove(3)
ValueError: list.remove(x): x not in list
## 리스트 내에 제거할 원소가 있어야 한다

>>> for i in b:
	b.remove(1)
	print(b)

[1, 1, 66, 88, 99]
[1, 66, 88, 99]
[66, 88, 99]
profile
wanna be idéal DE

0개의 댓글

관련 채용 정보