본문 바로가기
코딩 연습/코딩배우기

[python] 파이썬 문자열 관련 함수들

by good4me 2020. 9. 27.

goodthings4me.tistory.com

 

■ 문자열과 연산자('+', '*' 연산자) 

str1 = 'This is a'
str2 = 'short string.'

print('{0:s}'.format(str1 + str2))
# This is ashort string.

print('{0:s} {1:s} {2:s}'.format('She is', 'very ' * 4, 'beautiful.'))
# She is very very very very  beautiful.

 

■ split() 함수

  • 문자열을 나누어 리스트로 반환. 
  • 인자는 2개(대상 문자열, 수행될 횟수)인데, 첫 번째 인자만 넣어도 됨
  • split()의 default 인자는 공백(' ')임
str1 = 'My deliverable is due in May'
str1_list1 = str1.split()
str1_list2 = str1.split(' ', 2)

print(str1_list1)
# ['My', 'deliverable', 'is', 'due', 'in', 'May']

print(str1_list2)
# ['My', 'deliverable', 'is due in May']

print('index 1은 {0}, index 5는 {1}, index -1은 {2}'.format(str1_list1[1],\
        str1_list1[5], str1_list1[-1]))
# index 1은 deliverable, index 5는 May, index -1은 May

 

join() 함수

  • 리스트에 속한 문자열들을 하나의 문자열로 결합해줌. 
  • 함수명 앞에 하나의 인자를 받는데, 이 인자는 문자열 사이에 입력될 문자를 의미함
print(', '.join(str1_list1))
# My, deliverable, is, due, in, May

good4me.co.kr

 

strip() 함수

  • 문자열 끝에서 원하지 않는 문자(공백, 탭, 개행문자 등) 지움
  • 좌측 lstrip(), 우측 rstrip() 양쪽은 strip()
str3 = '  Remove  unwanted characters  from this string.\t\t   \n'

print(str3.strip())
# Remove   unwanted characters   from this string.
print(str3.lstrip())
# Remove   unwanted characters   from this string.  

print(str3.rstrip())
#   Remove   unwanted characters   from this string.


str4 = "$$Here's another string that has unwanted chatacrters.__--++"
print(str4.strip('$_-+'))
# Here's another string that has unwanted chatacrters.

 

replace() 함수

  • 문자열 내 하나의 문자나 문자열을 다른 문자 또는 문자열로 치환함
  • 첫번째 인자는 치환 대상 문자(열), 두번째 인자는 치환하고싶은 문자
str5 = "Let's replace the spaces in this sentence with other characters."
print(str5.replace(' ', '_'))
# Let's_replace_the_spaces_in_this_sentence_with_other_characters.

 

lower(), upper(), capitalize()

  • 영문 문자(열)에 대해 전체 소문자로, 전체 대문자로, 첫글자를 대문자로 등 변경함
str6 = 'Here is WHAT Happens When You Use lower, upper, Capitalize.'
print(str6.lower())
# here is what happens when you use lower, upper, capitalize.
print(str6.upper())
# HERE IS WHAT HAPPENS WHEN YOU USE LOWER, UPPER, CAPITALIZE.
print(str6.capitalize())
# Here is what happens when you use lower, upper, capitalize.

 

[참고] Foundations for Analytics with Python - 파이썬 데이터 분석 입문

 

댓글