상세 컨텐츠

본문 제목

파이썬 - 문자열 자료형

프로그래밍 언어/파이썬

by 별을 보는 사람 2020. 8. 22. 22:17

본문

반응형

문자열 자료형

 

문자열이란 문자, 단어 등으로 구성된 문자들의 집합을 의미한다.

 


print('spam eggs') 
spam eggs

 


print('doesn\'t') 
doesn't

print("doesn't") # doesn't

print('"Yes," they said.') 
"Yes," they said.

print("\"Yes,\" they said.") 
"Yes," they said.

print('"Isn\'t," they said.') 
"Isn't," they said.

 


print('C:\some\name')
C:\some
ame

print(r'C:\some\name') 
C:\some\name

 


print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

 


'ium' 다음에 'un' 세번 반복
print(3 * 'un' + 'ium')
unununium

 


print('Py' 'thon')
Python

 


text = ('Put several strings within parentheses '
           'to have them joined together.')
print(text)
Put several strings within parentheses to have them joined together.

 


print('풍선')
풍선

print("나비")
나비

print("ㅋㅋㅋㅋㅋㅋㅋㅋㅋ")
ㅋㅋㅋㅋㅋㅋㅋㅋㅋ

print("ㅋ"*9)
ㅋㅋㅋㅋㅋㅋㅋㅋㅋ

 


문자 연결 시 변수나 식은 사용할 수 없다.
prefix = 'Py'
print(prefix 'thon') # SyntaxError 발생
print(('un' * 3) 'ium') # SyntaxError 발생

변수와 문자를 연결에는 +를 사용한다.
print(prefix + 'thon')
Python

 


문자열은 0부터 시작하는 
word = 'Python'
print(word[0]) # P 앞에서 1번째 문자
print(word[5]) # n 앞에서 6번째 문자
print(word[-1]) # n 뒤에서 1번째 문자
print(word[-2]) # o 뒤에서 2번째 문자
print(word[-6]) # P 뒤에서 6번째 문자
print(word[0:2]) # 첫 문자에서 시작해 2문자 출력
print(word[0:4]) # 첫 문자에서 시작해 4문자 출력
print(word[:2] + word[2:]) # Python
print(word[:4] + word[4:]) # Python

예외 발생하는 경우과 그렇지 않은 경우
print(word[43]) # -> IndexError 발생
print(word[4:42]) # -> 예외 발생 안함
print(word[42:]) # -> 예외 발생 안함

Python 문자열은 immutable(불변)이기 때문에 문자 삽입 시 에러 발생
print(word[0] = 'J') # SyntaxError 발생
print('J' + word[1:]) # Jython
print(word[2:] = 'py') # SyntaxError 발생
print(word[:2] + 'py') # Pypy

 


len() : 문자열의 문자수를 리턴하는 함수 
s = 'supercalifragilisticexpialidocious'
print(len(s)) # 34
반응형

관련글 더보기

댓글 영역