728x90
문자열 메소드
str.find(sub) | str에서 맨 앞에 나타나는 sub의 시작 인덱스를 리턴, 없으면 -1을 리턴 |
str.index(sub) | str에서 맨 앞에 나타나는 sub의 시작 인겍스를 리턴, 없으면 Value Error 오류 발생 |
str.rfind(sub) | str에서 맨 뒤에 나타나는 sub의 시작 인덱스를 리턴, 없으면 -1 리턴 |
str.startswith(perfix) | str이 perfix로 시작하면 True, 아니면 False를 리턴 |
str.endswith(suffix) | str이 suffix로 끝나면 True, 아니면 False를 리턴 |
1. 처음 나타나는 문자열 하나만 찾기
입력용 파일
코드
def find_1st(filename,x) : #(파일이름,찾을문자)
infile = open(filename,"r") #읽을 파일
outfile=open("result.txt","w") #결과 저장용 파일
text = infile.read() # text에 입력용 파일의 텍스트를 넣음
position = text.find(x) # 문자를 찾는다
if position == -1 :
outfile.write(x+" is not found.\n") # 찾는 문자가 없을 경우
else :
outfile.write(x+" is at "+str(position)+" the 1st time.\n")
#찾는 문자가 존재할 경우
outfile.close() #파일닫기
infile.close() #파일닫기
print("Done") #실행 완료 확인
find_1st("filename.txt","s") # 함수 실행
결과 파일
위와 같은 텍스트 파일이 생성된다.
2. 둘째로 나타나는 문자열 하나만 찾기
입력용 파일은 1번과 같습니다.
코드
def find_2nd(filename,x) :
infile = open(filename,"r")
outfile=open("result.txt","w")
text = infile.read()
position = text.find(x)
position = text.find(x,position+1) #이전에 찾은 인덱스 다음부터 다시 처음으로 나타나는 위치를 찾는다.
if position == -1 :
outfile.write(x+" is not found.\n")
else :
outfile.write(x+" is at "+str(position)+" the 2nd time.\n")
outfile.close()
infile.close()
print("Done")
find_2nd("filename.txt","o")
결과 파일
728x90
'공부 > python' 카테고리의 다른 글
[python파이썬]백준 10951번 : A+B - 4 (0) | 2023.06.23 |
---|---|
[python파이썬] 포매팅 format() (0) | 2023.06.23 |
[python파이썬] strip()/split()/partition() 문자열 나누기 (0) | 2023.06.07 |
[python파이썬] 텍스트 파일 읽고 쓰기 (2) | 2023.06.05 |
[python파이썬] 집합과 딕셔너리 (0) | 2023.05.31 |