인공지능 개발자 수다(유튜브 바로가기) 자세히보기

파이썬/코딩테스트

[자료구조] 문자열 (파이썬)

Suya_03 2024. 4. 20. 21:53

목차

    반응형

    이번시간에는 문자열 사용방법에 대해 알아봅시다.

    문자열도 마찬가지로 코딩테스트에서는  빠르게 처리할 수 있는 능력이 필요하다. (오래 걸리면 곤란하다)

     

    1. 문자열 선언과 초기화

    # 문자열을 선언하고 초기화하는 여러 방법
    string1 = "안녕하세요"
    string2 = '코딩 테스트 준비 중입니다'
    string3 = """여러 줄에 걸쳐 문자열을
    작성할 때는 이렇게
    작성할 수 있습니다."""
    
    # 출력해보기
    print(string1)
    print(string2)
    print(string3)

     

    2. 문자열 인덱싱과 슬라이싱

    문자열의 슬라이싱도 마찬가지로

    시작 인덱스는 포함하지만

    마지막 인덱스는 포함하지 않는 것을 주의한다.

     

    그리고, 음수를 사용할 때에는

    시작 인덱스는 마찬가지로 포함

    마지막 인덱스를 포함한다. (-1로 했을 때 마지막 문자를 포함한 것을 볼 수 있음)

    # 문자열 선언
    s = "Hello, Python!"
    
    # 인덱싱: 문자열에서 특정 위치의 문자 하나를 가져옵니다.
    print(s[0])  # 'H'
    print(s[-1]) # '!' (마지막 문자)
    
    # 슬라이싱: 문자열에서 지정된 범위의 문자들을 가져옵니다.
    print(s[0:5])   # 'Hello' (인덱스 0부터 4까지)
    print(s[7:13])  # 'Python' (인덱스 7부터 12까지)
    print(s[:5])    # 'Hello' (처음부터 인덱스 4까지)
    print(s[7:])    # 'Python!' (인덱스 7부터 끝까지)
    print(s[-7:-1]) # 'Python' (뒤에서 7번째부터 뒤에서 1번째 전까지)

     

    3. 문자열 조작

    3.1. 문자열 깔끔하게 정리

    • lower
      • 소문자로 변경
    • upper
      • 대문자로 변경
    • strip()
      • 문자열의 양쪽 끝 공백을 제거한다. (문자열 사이에 있는 공백은 제거하지 않음)
    # 문자열 선언
    text = "Hello, Python!"
    
    # lower() 메소드: 문자열의 모든 대문자를 소문자로 변환합니다.
    print(text.lower())  # 'hello, python!'
    
    # upper() 메소드: 문자열의 모든 소문자를 대문자로 변환합니다.
    print(text.upper())  # 'HELLO, PYTHON!'
    
    
    # 문자열 선언
    text = "   Hello, Python!   "
    
    trimmed_text = text.strip()
    print(trimmed_text)  # 공백이 제거된 문자열 출력

     

    4.2. 문자열 결합과 분리 반복

    • + 연산자
      • 두개의 문자열을 이어붙인다.
    • * 연산자
      • 문자열을 여러번 반복한다.
    # 문자열 결합
    greeting = "Hello"
    name = "Alice"
    message = greeting + ", " + name + "!"
    print(message)  # 'Hello, Alice!'
    
    # 문자열 반복
    laugh = "ha"
    print(laugh * 3)  # 'hahaha'

     

    • 문자열 결합 - '구분자'.join(반복 가능한 객체)
      • 리스트, 튜플 등의 iterable객체를 입력으로 받는다.
      • '' 안에 있는 문자열을 구분자로 이어붙인다.
    # 문자열 결합 with join() 메소드
    words = ["Python", "is", "fun"]
    sentence = " ".join(words)
    print(sentence)  # 'Python is fun'

     

    • 문자열 분리 - split
      • 문자열을 분리하고 list로 반환한다.
      • 파라미터로, 분리 기준을 넣어줄 수 있다. (default는 공백문자(' ')이다.)
    text = "Hello, Python! Welcome to the world of Python."
    
    # 공백을 기준으로 문자열 분리
    words = text.split()
    print(words)  # ['Hello,', 'Python!', 'Welcome', 'to', 'the', 'world', 'of', 'Python.']
    
    # 쉼표를 구분자로 사용하여 문자열 분리
    parts = text.split(',')
    print(parts)  # ['Hello', ' Python! Welcome to the world of Python.']
    
    # 쉼표를 구분자로 사용하고, 최대 1번만 분리
    limited_split = text.split(',', 1)
    print(limited_split)  # ['Hello', ' Python! Welcome to the world of Python.']

    4.3. 문자열 대체 및 제거

    • replace(a, b)
      • a문자열을 b문자열로 대체한다.
    # 문자열 교체
    original_text = "Hello, Python!"
    replaced_text = original_text.replace("Python", "World")
    print(replaced_text)  # 'Hello, World!'
    
    # 특정 문자 제거 (공백 제거 예시)
    spacey_text = "H e l l o"
    no_spaces = spacey_text.replace(" ", "")
    print(no_spaces)  # 'Hello'
    
    # 특정 문자 제거 (특정 문자열 제거 예시)
    remove_this = "remove"
    text_with_remove = "Here we should remove the word remove."
    clean_text = text_with_remove.replace(remove_this, "")
    print(clean_text)  # 'Here we should  the word .'
    
    # 여러 개의 문자를 제거할 때는 여러 replace를 연결하거나 정규 표현식을 사용할 수 있습니다.
    text_with_multiple_issues = "Some text, with, commas, and... periods."
    cleaned_text = text_with_multiple_issues.replace(",", "").replace("...", "")
    print(cleaned_text)  # 'Some text with commas and periods.'

     

    5. 문자열 찾기

    • find(문자열)
      • 지정된 문자열을 찾고, 그 위치의 첫 번째 인덱스를 반환
      • 찾고자 하는 문자열이 없다면 -1을 반환
    text = "Hello, Python programming!"
    
    # 'Python'의 위치 찾기
    position = text.find('Python')
    print(position)  # 출력: 7
    
    # 존재하지 않는 문자열 찾기
    not_found = text.find('Java')
    print(not_found)  # 출력: -1
    • index(문자열)
      • find()와 유사하게 작동하지만, 찾고자 하는 문자열이 문자열 내에 없을 경우 ValueError 예외를 발생
    text = "Hello, Python programming!"
    
    # 'Python'의 위치 찾기
    position = text.index('Python')
    print(position)  # 출력: 7
    
    # 존재하지 않는 문자열 찾기 (예외 발생)
    try:
        not_found = text.index('Java')
        print(not_found)
    except ValueError:
        print("The substring 'Java' was not found in the text.")

     

    6. 문자열 포매팅

    • f-string
      • 문자열 내에서 {}를 사용해 변수의 값을 직접 삽입할 수 있다.
    name = "Alice"
    age = 30
    height = 168.5
    
    # 간단한 f-string 사용
    message = f"Hello, {name}. You are {age} years old."
    print(message)
    
    # 수식 사용
    print(f"Next year, you will be {age + 1} years old.")
    
    # 함수 호출 사용
    def get_status(age):
        return "young" if age < 40 else "wise"
    
    print(f"{name} is {get_status(age)}.")
    
    # 포매팅 옵션 사용 (소수점 제한)
    print(f"{name} is {height:.1f} cm tall.")

     

     

    다음 글에서는 정규표현식에 대해 공부할 것이다.

    반응형