파이썬 문자열 정리

Python

Posted by kwon on 2019-10-17

파이썬의 문자열 함수에 대해 알아보자

문자열

문자열 생성 방법

문자열은 “” 또는 ‘’를 이용하여 만들 수 있다. “”안에는 ‘가 들어갈 수 있고, ‘’안에는 “가 들어갈 수 있다.

“”” “”” 또는 ‘’’ ‘’’ 을 이용해서 여러 줄의 문자열도 표현이 가능하다.

1
2
3
str = """Life is short,
you need python"""
print(str)

결과 : Life is short,

you need python

문자열 연산

  • 문자열 합치기 (str1 + str2)

    1
    2
    3
    str1 = "python is "
    str2 = "good!"
    print(str1 + str2)

    결과 : python is good!

  • 문자 반복

    1
    print('='*50)

    결과 : ==================================================

문자열 인덱싱과 슬라이싱

인덱싱은 해당 번호의 순서에 있는 데이터를 가져오는 것이고, 슬라이싱은 해당 범위 내의 데이터를 모두 가져오는 것이다.

리스트와 마찬가지로 사용하면 된다.

1
2
3
4
5
6
7
8
9
str = "Life is too short, You need Python."

print(str[0]) # 인덱스 0번 출력
print(str[12]) # 인덱스 12번 출력
print(str[0:12]) # 0부터 11까지 출력, 12는 출력 X
print(str[:12]) # 처음부터 인덱스 11까지 출력
print(str[12:]) # 인덱스 12 부터 끝까지 출력
print(str[-2]) # 뒤에서 두 번째 인덱스 출력
print(str[:-2]) # 처음부터 뒤에서 세 번째 인덱스까지 출력, 두번째는 출력 X

결과

1
2
3
4
5
6
7
8
9
10
11
12
13
L

s

Life is too

Life is too

short, You need Python.

n

Life is too short, You need Pytho

문자열 함수

  • 문자열 포맷팅 : format()
    format() 함수를 이용하면 서식문자와 같이 대입이 가능하다.

1

1
2
3
4
5
print("number : {0}".format(10)) # 숫자 대입
num = 10
print("number : {0}".format(num)) # 숫자 변수 대입
print("number : {0}, string : {1}".format(100, 'test')) # 두 개의 값 대입
print("number : {num}, string : {str}".format(num=100, str='test')) # 이름으로 대입

결과

1
2
3
4
5
6
7
number : 10

number : 10

number : 100, string : test

number : 100, string : test

2

1
2
pos = [12.5, 35, 90]
print("A의 좌표는 x = {p[0]}, y = {p[1]}, z = {p[2]}".format(p=pos))

결과

1
A의 좌표는 x = 12.5, y = 35, z = 90
  • 대소문자 변환 : upper(), lower()
1
2
3
str = "aBcdEFg"
print(str.upper()) # str의 모든 문자를 대문자로 변환
print(str.lower()) # str의 모든 문자를 소문자

결과

1
2
3
ABCDEFG

abcdefg
  • 첫 글자만 대문자, 나머지는 소문자로 변환 : capitalize()

a가 변하지는 않음.

1
2
3
a = "abcDef"
print(a.capitalize())
print(a)

결과

1
2
3
Abcdef

abcDef
  • 문자 위치 반환 : find(), index()
1
2
3
4
5
6
7
8
9
10
11
str = 'hello world!'

# str의 문자 중 'w'의 위치 반환
print(str.find('w'))
print(str.index('w'))

#find는 존재하지 않는 문자 검색시 -1반환
print(str.find('x'))

# index는 존재하지 않는 문자 검색시 에러 발생!!
print(str.index('x'))

결과

1
2
3
4
5
6

6

-1
  • 문자 수 세기, 삽입 : count(), join()
1
2
3
4
5
str = 'hello world!'
pick = ','

print(str.count('l')) # str의 해당 문자 수 반환
print(pick.join(str)) # str을 pick의 구분자를 포함하여 문자열 반환

결과

1
2
3
3

h,e,l,l,o, ,w,o,r,l,d,!
  • 공백 삭제 : lstrip(), rstrip(), strip()
1
2
3
4
5
6
str = '\t hello world! \t'

print(str)
print(str.lstrip()) # 왼쪽 공백 삭제
print(str.rstrip()) # 오른쪽 공백 삭제
print(str.strip()) # 양쪽 공백 삭제

결과

1
2
3
4
	 hello world! 	
hello world!
hello world!
hello world!
  • 문자열 치환, 나누기 : replace(), split()
1
2
3
4
5
6
str = 'hello world!'

print(str.replace('world', 'kwon')) # str의 world를 kwon으로 치환

print(str.split()) # str을 공백으로 나누어 리스트로 반환
print(str.split('o')) # str을 'o'를 기준으로 나누어 리스트로 반환

결과

1
2
3
4
5
hello kwon!

['hello', 'world!']

['hell', ' w', 'rld!']

문자열과 리스트 변환

리스트(List)를 특정 구분자를 포함에 문자열(String)로 반환

  • join()
1
2
3
list = ['k', 'w', 'o', 'n']
print(''.join(list)) # list를 공백없이 붙여 문자열로 변환
print('/'.join(list)) # list를 /를 구분자로 하여 문자열로 변환

결과

1
2
3
kwon

k/w/o/n

문자열(String)을 특정 ‘구분자’를 기준으로 리스트(List)로 변환

  • split()
1
2
3
4
5
6
str = 'python java c c++ c#'
print(str.split()) # 공백을 구분자로 하여 리스트로 변환
strlist = str.split()
print('/'.join(strlist)) # strlist를 /를 구분자로 하여 문자열로 변환
str = '/'.join(strlist)
print(str.split('/')) # /를 구분자로 하여 리스트로 변환

결과

1
2
3
4
5
['python', 'java', 'c', 'c++', 'c#']

python/java/c/c++/c#

['python', 'java', 'c', 'c++', 'c#']

참조
https://ledgku.tistory.com/44
https://wikidocs.net/16034