[python파이썬] 문자열 검색

2023. 6. 5. 02:38·공부/python
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
'공부/python' 카테고리의 다른 글
  • [python파이썬] 포매팅 format()
  • [python파이썬] strip()/split()/partition() 문자열 나누기
  • [python파이썬] 텍스트 파일 읽고 쓰기
  • [python파이썬] 집합과 딕셔너리
knhoo
knhoo
  • knhoo
    &*
    knhoo
  • 전체
    오늘
    어제
    • 전체 (139)
      • Unity 개발일지 (1)
        • [Unity2D]졸업프로젝트 (17)
        • [Unity3D]VR프로젝트 (2)
      • 공부 (115)
        • 부트캠프 (12)
        • C++ (39)
        • Unity & C# (8)
        • 데이터베이스 (2)
        • 컴퓨터비전 (0)
        • 컴퓨터구조 (0)
        • python (7)
        • BAEKJOON (36)
        • 개발 (2)
        • 자료구조 (9)
      • 일상 (2)
  • 블로그 메뉴

    • Github
    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

    • 📖README
  • 인기 글

  • 태그

    패널파워
    자료구조
    앱테크
    c#
    Cpp
    캐시워크
    비트버니
    머니워크
    unity
    백준 #python
    til
    Python
    티스토리챌린지
    unity2d
    멋쟁이사자처럼후기
    구간합
    오블완
    야핏무브
    C++
    백준
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
knhoo
[python파이썬] 문자열 검색
상단으로

티스토리툴바