Tech & Development/Programming Languages
[Python] 문자열에서 특정문자 제거
[Python] 문자열에서 특정문자 제거
2023.01.191. replace() method replace() 메서드는 문자열에서 특정 문자나 문자열을 다른 문자나 문자열로 대체합니다. 예를 들어, 문자열 "Hello World!"에서 "o"를 제거하려면 다음과 같이 할 수 있습니다. string = "Hello World!" new_string = string.replace("o", "") print(new_string) # "Hell Wrld!" 2. translate() method translate() 메서드 역시 문자열에서 특정 문자를 제거할 수 있습니다. string = "Hello World!" remove_chars = "o" new_string = string.translate(string.maketrans("", "", remove_chars..
[Python] 자료형 - 리스트 (List)
[Python] 자료형 - 리스트 (List)
2023.01.18Python에서 list는 순서가 있는 요소들의 집합을 나타내는 객체입니다. list 객체는 인덱싱, 슬라이싱, 연산, 관련된 함수들(append, extend, insert, remove, pop, count, sort, reverse, ...)를 지원합니다. 순서를 가지며, 인덱싱, 슬라이싱 기능을 지원 수학적 집합의 특성을 가지며, 중복된 요소를 가질 수 있음 변경 가능(mutable) 객체 요소들의 순서를 유지하며, 인덱싱, 슬라이싱 기능을 지원 # list 생성 lst = [1, 2, 3, 4, 5] print(lst) # [1, 2, 3, 4, 5] # list 요소 추가 lst.append(6) print(lst) # [1, 2, 3, 4, 5, 6] # list 요소 제거 lst.remov..
[Python] 자료형 - 집합(Set)
[Python] 자료형 - 집합(Set)
2023.01.18Python에서 set 자료형은 순서가 없고, 중복되지 않는 요소들의 집합을 나타내는 객체입니다. set 객체는 집합 연산(union, intersection, difference, symmetric difference)을 지원하며, 관련된 함수들(add, remove, discard, clear, pop, ...)를 지원합니다. set 객체는 순서를 가지지 않으며, 인덱싱, 슬라이싱 기능을 지원하지 않음 set 객체는 수학적 집합의 특성을 가지며, 중복된 요소를 가질 수 없음 set은 변경 가능(mutable) 객체 set 객체는 요소들의 순서가 없기 때문에, 특정 요소가 있는지 확인하는 것은 O(1) 의 시간 복잡도 # set 생성 s = set([1, 2, 3, 4, 5]) print(s) # {1..
[Python] 텍스트 파일에 내용 추가
[Python] 텍스트 파일에 내용 추가
2023.01.18Python에서 텍스트 파일에 내용을 추가하려면, 먼저 파일을 열어야 합니다. 파일을 추가 모드로 열려면 open 시 mode에 'a'를 입력하여 append 파일 모드를 사용해야 합니다. 파일을 열고 파일에 내용을 추가 하기 위해서 file.write() 함수를 사용합니다. with open("example.txt", "a") as file: file.write("This text will be added to the file.") 다른 방법으로는 아래와 같이 작성 할 수 있습니다. f = open("example.txt", "a") f.write("This text will be added to the file.") f.close() 더보기 참고 : 'w' 파일 모드를 사용하면 파일을 쓰기 모드로 열..
[Python] File 끝 확인
[Python] File 끝 확인
2023.01.18Python 파일의 끝을 찾기 위한 방법을 소개하겠습니다. 파일을 읽어들이는 open() 함수를 사용합니다. 예를 들어, myfile.txt라는 파일을 읽어들이는 경우 아래와 같은 코드를 사용할 수 있습니다. with open("myfile.txt", "r") as f: lines = f.readlines() print(lines[-1]) 위 코드에서 readlines() 함수를 사용하여 파일의 모든 라인을 읽어들입니다. 그리고 lines 리스트의 마지막 요소를 출력하면 파일의 끝을 찾을 수 있습니다. 간편하게 파일을 열고 닫기 위해서 with open을 사용하였습니다. (파일을 읽어들이는 경우 seek() 함수를 사용하여 파일의 끝에서부터 일정 길이만큼 파일을 읽어들일 수도 있습니다.) read(), ..
[Python] File 수정, 생성 시간 확인하기
[Python] File 수정, 생성 시간 확인하기
2023.01.18Python으로 파일 수정 시간, 생성 시간을 확인하려면 os.path 모듈을 사용할 수 있습니다. import os file_path = "path/to/file.py" modification_time = os.path.getmtime(file_path) creation_time = os.path.getctime(file_path) print("Modification time:", modification_time) print("Creation time:", creation_time) 위 코드에서 os.path.getmtime(file_path)는 파일의 수정 시간을 반환하며, os.path.getctime(file_path)는 파일의 생성 시간을 반환합니다. Output: Modification tim..
[Python] File 개수 확인
[Python] File 개수 확인
2023.01.18Python으로 파일 개수를 확인하려면, 먼저 해당 폴더에 있는 파일들을 리스트로 받아와야 합니다. 그리고 그 리스트의 길이를 확인하면 파일 개수를 알 수 있습니다. import os folder_path = "path/to/folder" file_list = os.listdir(folder_path) file_count = len(file_list) print(file_count) Output : 13 파일 개수를 확인하는 다른 방법은 glob 라이브러리를 사용하면 특정 경로에 있는 파일들을 패턴으로 찾을 수 있습니다. folder_path + '/*'라는 패턴으로 해당 폴더 안에 있는 모든 파일을 찾아서 그 개수를 확인합니다. import glob folder_path = "path/to/folder..
[Python] 문자열 줄바꿈 하는 방법
[Python] 문자열 줄바꿈 하는 방법
2023.01.17Python에서는 개행 문자 \n을 사용하여 문자열에 줄 바꿈을 추가할 수 있습니다. 예를 들면 다음과 같습니다. string = "This is the first line.\nThis is the second line." print(string) Output: This is the first line. This is the second line. 문자열 클래스의 join() 메서드를 사용하여 여러 문자열을 줄바꿈으로 합칠 수도 있습니다. 예를 들면 다음과 같습니다. lines = ["This is the first line.", "This is the second line."] string = "\n".join(lines) print(string) 이렇게 하면 위의 Output과 동일하게 출력됩니다. ..
[Python] dictionary를 JSON으로 변환
[Python] dictionary를 JSON으로 변환
2023.01.17Python에서는 json module의 json.dumps() Method를 사용하여 dictionary를 JSON 문자열로 변환합니다. import json my_dict = {'a': 1, 'b': 2, 'c': 3} json_string = json.dumps(my_dict) print(json_string) Output : '{"a": 1, "b": 2, "c": 3}' json.dump() Method를 사용하여 JSON 문자열을 파일로 저장할 수 있습니다. with open("data.json", "w") as f: json.dump(my_dict, f) json.dumps() 메서드에는 추가 파라미터를 지정할 수 있습니다. indent, separators, sort_keys 등이 있습니다..
[Python] *args와 **kwargs 사용방법
[Python] *args와 **kwargs 사용방법
2022.11.21Python에서 *args, **kwars를 사용하는 함수를 볼 때가 있습니다. C를 접하신분은 * 를 보고 Python에도 포인터가 있다고 오해할 수도 있지만 다행히도 포인터는 아닙니다. 분명 arguments를 받는 인자인 것 같은데, Python 입문자들을 혼동스럽게 만드는 *args와 **kwars에 대해서 알아보겠습니다. (작성 하실 때 *args와 **kwars 라는 이름을 사용할 필요는 없습니다. args와 kwars는 변수명이기때문에 다른 변수명 앞에 * 또는 **를 붙여 사용하면 됩니다. 예를들어 *vars나 **arguments 등으로 바꾸어 사용하시면 됩니다.) 간단히 argument를 입력받아 print하는 예를 들겠습니다. def print_args(arg1, arg2): prin..
[Python] dictionary(딕셔너리) Value로 Key찾기
[Python] dictionary(딕셔너리) Value로 Key찾기
2022.06.10Python에서 dictionary(딕셔너리) 타입은 immutable한 키(key)와 mutable한 값(value)으로 맵핑되어 있는 순서가 없는 집합입니다. 일반적인 딕셔너리 타입은 중괄호로 되어 있고 키와 값으로 이루어져 있습니다. test_dict = {'0': 'AA', '1': 'BB', '2': 'CC', '3': 'DD'} test_dict >> {'0': 'AA', '1': 'BB', '2': 'CC', '3': 'DD'} key를 이용하여 value를 찾는 방법은 다음과 같습니다. test_dict.get('3') >> 'CC' test_dict['3'] >> 'CC' 반대로 value를 이용해 key를 찾는 방법은 다음과 같습니다. [k for k, v in test_dict.ite..
[Python] 문자열에서 숫자만 추출하기
[Python] 문자열에서 숫자만 추출하기
2022.03.301. 모든 숫자들을 1개의 문자열로 추출 : re.sub() sub()는 string에서 pattern과 일치하는 문자들을 repl로 교체합니다. re.sub(pattern, repl, string) 다음과 같이 sub()를 사용하여 문자열에서 숫자가 아닌 문자를 모두 제거하고 숫자로 구성된 문자열을 만들 수 있습니다. import re string = 'aaa1234, ^&*2233pp' numbers = re.sub(r'[^0-9]', '', string) print(numbers) Output: 12342233 2.연속된 숫자들을 추출하여 List로 리턴 : re.findall() re.findall(pattern, string)은 string에서 pattern에 해당하는 내용들을 찾아서 리스트로 ..