본문 바로가기
Python

[Python] 문자열

by 기리의 개발로그 2023. 12. 22.

문자열

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


문자열 선언


파이썬에서 문자열을 표현하기 위해서는 아래와 같이 4가지 방법이 있다.

큰따옴표("), 작은따옴표('), 큰따옴표 3개("""), 작은따옴표 3개(''')

string = "Hello World"
string = 'Hello World'
string = """Hello World"""
string = '''Hello World'''

print(string)
Hello World

문자열에 따옴표 포함

문자열에 따옴표를 포함하고 싶은 경우가 있다.

  • 작은따옴표 포함
    작은 따옴표를 포함하기 위해서는 큰따옴표로 문자열을 만든다.
test = "Python's favorite food is perl"

print(test)
Python's favorite food is perl

  • 큰따옴표 포함
    큰 따옴표를 포함하기 위해서는 작은따옴표로 문자열을 만든다.
test = '"Python is very easy." he says.'

print(test)
"Python is very easy." he says.

  • \를 사용하여 따옴표 포함
    \', \" 를 이용하여 문자열에 큰따옴표나 작은따옴표를 포함시킬 수 있다.
test1 = 'python\'s favorite food is perl'
test2 = "\"python is very simple\" he said"

print(test1)
print(test2)
python's favorite food is perl
"python is very simple" he said

여러 줄의 문자열을 하나의 변수에 선언

  • \n 사용
multiline = "python \nmultiline is \neasy"

multiline = '''
python 
multiline is 
easy
'''
multiline = """
python 
multiline is 
easy
"""

print(multiline)
python
multiline is
easy

문자열 연산


다른 언어와 달리 파이썬에서는 문자열을 더하거나 곱할 수 있다.


문자열 덧셈

a + b 의 경우 a와 b 문자열을 합치라는 의미이다.

head = "yang"
body = "sanggil"

print(head + body)
yangsanggil

문자열 곱셈


a * 5의 경우 a 문자열을 5번 반복하라는 의미이다.

a = "sanggil"

print(a * 2)
sanggilsanggil

또한, 아래와 같이 응용할 수 있다.

a = "=" * 50
b = "\nPython\n"
c = "=" * 50

print(a + b + c)
==================================================
Python
==================================================
반응형

'Python' 카테고리의 다른 글

[Python] 리스트  (31) 2023.12.28
[Python] 문자열 내장함수  (33) 2023.12.27
[Python] 문자열 포맷팅  (45) 2023.12.26
[Python] 연산자  (23) 2023.12.21
[Python] 변수 및 기본 자료형  (46) 2023.12.20

댓글