Ramanu
파이썬 코딩 skill 정리 본문
# python3 기준
파이썬 코딩할 때 자주 사용하는 기술 정리(계속 추가예정..)
1. 리스트 공백 제거
data = [idx for idx in data if idx]
2. 리스트 중복제거
1) for 구문
data1 = []
for idx in data:
if idx not in data1:
data1.append(idx)
2) set 이용
data = list(set(data))
3. hex string을 byte값으로 변환하는 방법
ex) '1f'(string) -> \x1f
data = '1f'
data = bytes.fromhex(data)
>>> b'\x1f'
https://stackoverflow.com/questions/5649407/hexadecimal-string-to-byte-array-in-python
hexadecimal string to byte array in python
I have a long Hex string that represents a series of values of different types. I wish to convert this Hex String into a byte array so that I can shift each value out and convert it into its proper...
stackoverflow.com
4. 특정 값을 가지고 있는 파일이름 찾기
ex) filename = test_test
def find_file(name, path):
for idx in os.listdir(path):
if os.path.isfile(os.path.join(path,idx)) and name in idx:
return idx
a = find_file("test", "./")
print(a)
>> test_test
5. index 정리
ex) 2를 002로 바꾸고 싶을 때 사용
"2".zfill(3)
6. string to int or dictionary
ex) "123"(str) > 123(int) 또는 "{"1": 1, "2": 2}"(str) > {"x": 1, "y": 2}(dictionary)
import ast
# case 1
a = "123" # type: str
a_int = eval(a)
print(type(a_int), a_int)
>> (<type 'int'>, 123)
# case 2
a = "{\"x\":1, \"y\":2}" # type: str
a_dic = ast.literal_eval(a) # eval도 사용가능
print(type(a_dic), a_dic)
>> <class 'dict'> {'x': 1, 'y': 2}
tip) dictionary 중, key나 value에 ""이 없는 string이 들어온다면 error가 출력됨(하나의 변수값으로 인식하는 듯)
> ex) ast.literal_eval("{"a": true}")
> ValueError: malformed node or string
> replace("true", "\"true\"") 사용 시 해결 가능
'파이썬' 카테고리의 다른 글
파이썬 주석(#) 정규식 (0) | 2022.05.13 |
---|