Skip to content

Python:String

Python문자열에 관련 내용을 정리한다.

String literals

r 문자는 raw string으로 백슬래시 문자를 해석하지 않고 남겨두기 때문에 정규표현식과 같은 곳에 유용하다. 예를 들어 r문자를 사용하지 않는다면

re.compile('(\\d+)/(\\d+)/(\\d+)')

와 같이 길어 백슬래시를 두 번 사용해야 하는 불편함이 있다. 그래서 보통 r문자를 붙여준다.

Functions

  • split(param1): 문자열을 분할한다. param1 문자열로 분할한다.
  • find: 문자열을 찾는다.
  • rfind: 역순으로 문자열을 찾는다.
  • strip: 문자 앞과 끝의 공백 제거(Trim).
  • replace: 문자열 교환.

Replace

a = "Life is too short"
a.replace("Life", "Your leg")

Use Regexp

import re
article = re.sub(r'(?is)</html>.+', '</html>', article)

Format string

포맷 문자열은 아래와 같이 적용한다.

print "Result: {0}, {1}".format(string1, string2)

또는

print "Result: %s, %s" % (config.version, VERSION_MIN)

Insert string

문자열 추가는 아래와 같이 적용한다.

def insert_dash(string, index):
    return string[:index] + '-' + string[index:]

print insert_dash("355879ACB6", 5)

Multiline strings

문자열을 여러줄에 걸쳐 적용하고 싶을 경우 아래와 같이 사용한다.

string = """line one
line two
line three"""

또는

string = ("this is an "
    "implicitly joined "
    "string")

또는

string = "this is an " + \
    "implicitly joined " + \
    "string"

또는

string = "this is an " \
    "implicitly joined " \
    "string"

Favorite site

References


  1. Jump_to_Python_-_String.pdf