ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python] 문자열 메소드
    자료구조 2022. 9. 29. 22:40

    1. A.join(B)

    리스트 B에 있는 모든 요소를 A를 사용해 하나의 문자열로 결합해준다.

    >>> test_list = ['a','b','c','d']
    >>> " ".join(test_list)
    'a b c d'

    2. A.format() 

    문자열 A에 변수를 추가하거나 형식화하는데 사용

    (의외로 유용하게 쓰이는 경우가 꽤 있다!!)

    >>> "이름 : {who}, 특기 : {what}".format(who="heejoo", what="deep learning")
    '이름 : heejoo 특기 : deep learning'

    3. locals()

    현재 스코프에 있는 지역 변수를 딕셔너리로 변환

    (여기서 ** 연산자의 의미 : 함수로 전달하기에 적절한 키-벨류 딕셔너리가 생성된다 )

    >>> name = "heejoo"
    >>> job = "AI scientist"
    >>> "{name} : {job}".format(**locals())
    'heejoo : AI scientist'

    4. A.split(t,n)

    문자열 A에서 문자열 t를 기준으로 정수 n번만큼 분리한 문자열 리스트를 반환

    n을 지정하지 않을 경우 : 대상 문자열을 t로 최대한 분리

    t를 지정하지 않을 경우 : 공백 문자로 구분한 문자열 리스트 반환

    (비슷하게 rsplit은 문자열을 오른쪽에서 왼쪽으로 분리한 문자열 리스트 반환)

    >>> start = 'a*b*!'
    >>> start.split('*',1)
    ['a','b*!']
    >>> start.rsplit('*',1)
    ['a*b','!']

    💟 문제 : 주어진 문자열에서 사용된 모든 단어를 알파벳 순으로 출력하며 각 단어가 등장한 횟수도 함께 출력하시오

    import string
    import sys
    
    def count_unique_word():
    	words = {}  // 딕셔너리로 틀을 만든다!
        strip = string.whitespace + string.punctuation + string.digits + "\"'"
        for word in lines.lower().split():
        	word = word.strip(strip)
            if len(word)>2:
            	words[word] = words.get(word,0)+1
        for word in sorted(words):
        	print("{0}: {1}번".format(word, words[word]))

    5. A.count(sub, start, end)

    문자열 A에서 인덱스 start, end 범위 내의 부분 문자열 sub가 나온 횟수를 반환한다.

    >>> word = 'hello python hello again and hello'
    >>> word.count('hello',0,-1)
    2
    >>> word.count('hello')
    3

    6. A.replace(old, new, maxreplace)

    문자열 A에서 문자열 old를 대체 문자열 new로 maxreplace만큼 변경한 문자열의 복사본을 반환한다.

    (maxreplace를 지정하지 않으면 모든 old를 new로 대체한다.)

    >>> word = 'hello python hello again and hello'
    >>> word.replace("hello", "bye", 2)
    'bye python bye again and hello"

    7. f-string

    문자열 앞에 접두사 f를 붙여 사용

    기존의 %나 .format 방식에 비해 간결하고 직관적이며 속도도 빠르다!

    >>> name = 'hijoo'
    >>> f"나의 이름은 {name}입니다."
    "나의 이름은 hijoo입니다."

    '자료구조' 카테고리의 다른 글

    [Python] DFS , BFS (1)  (0) 2022.10.05
    [Python] 그리디 알고리즘  (0) 2022.10.05
    코딩테스트 기초  (1) 2022.10.05
    [Python] 순열과 동적계획법  (0) 2022.10.04
    [Python] 튜플과 리스트  (0) 2022.10.04

    댓글

Designed by Tistory.