파이썬(Python)/문법

[Python] String 단어 나누기, 단어 바꾸기 (split, replace)

끄적끄적아무거나 2021. 10. 13. 13:54
반응형

 

목차

     

     

     

     


     

    Python String 단어 나누기 함수

     

    String에 내장된 함수로 split를 사용하면 string 안의 단어를 나눠 줄 수 있습니다. Syntax는 아래와 같습니다. 

     

    • string.split(separator, maxsplit)

     

    parameter 값으로 separator와 maxsplit이 있습니다.

     

     

    • separator : 나누는 기준점, default는 띄워쓰기(스페이스) 입니다.
    • maxsplit : 몇 개까지 나눌지를 정합니다. default는 -1이고 의미는 모든 경우입니다.

     

     

    예제 코드>>

    words = "HelLo, mY nAme is Scribble"
    print(words.split())
    print(words.split(","))

     

    결과>>

    ['HelLo,', 'mY', 'nAme', 'is', 'Scribble']
    ['HelLo', ' mY nAme is Scribble']

     

     

     

     

    Python String 단어 바꾸기 함수

     

    String에 내장된 함수로 replace를 사용하면 string 안의 단어를 변경할 수 있습니다. Syntax는 아래와 같습니다. 

     

    • string.replace(oldvalue, newvalue, count)

     

    parameter 값으로 oldvalue와 newvalue와 count가 있습니다.

     

     

    • oldvalue: 바꾸기 전 값
    • newvalue: 바꿀 값
    • count

     

     

    예제 코드>>

    words = "HelLo, HelLo mY nAme is Scribble"
    print(words.replace("HelLo","Hi"))
    print(words.replace("HelLo","Hi",1))

     

    결과>>

    Hi, Hi mY nAme is Scribble
    Hi, HelLo mY nAme is Scribble

     

     

     

     

    반응형