3. 문자열
문자열은 문자로 이루어진 데이터의 집합입니다.
문자열을 만들기 위해서는 따옴표를 사용하면 되는데,
큰따옴표 or 작은따옴표 둘 중 아무거나 사용하면 됩니다.
s1 = 'This is String'
s2 = "This is String"
print(s1)
print(s2)
>> 실행결과
This is String This is String |
큰따옴표와 작은따옴표 모두 사용하는 이유는 문자열 안에서 따옴표를 사용하기 위함입니다.
s3 = 'one "two" three'
s4 = "one 'two' three"
print(s3)
print(s4)
>> 실행결과
one "two" three one 'two' three |
여러 줄의 문자열을 사용하기 위해서는 따옴표를 3개 사용하면 됩니다.
s5 = '''first line
second line
third line'''
s6 = """first line
second line
third line
"""
print(s5)
print("\n")
print(s6)
>> 실행결과
first line second line third line first line second line third line |
3.1 이스케이프 문자
문자열에 탭이나 줄 바꿈 등 여러 문자를 사용하기 위해서는 다음과 같이 사용해야 합니다.
탭 : \t
엔터 : \n
역슬래시 : \\
s1 = "Escape character"
s2 = "Escape\tcharacter"
s3 = "Escape\ncharacter"
s4 = "Escape character\\"
print(s1)
print(s2)
print(s3)
print(s4)
>> 실행결과
Escape character Escape character Escape character Escape character\ |
3.2 title()
title()을 사용하면 각 단어의 첫 글자를 대문자로 변경할 수 있습니다.
s1 = "how to set a good goal"
print(s1)
print(s1.title())
>> 실행결과
how to set a good goal How To Set A Good Goal |
3.3 upper()
upper()을 사용하면 문자열 전체를 대문자로 변경할 수 있습니다.
s1 = "how to set a good goal"
print(s1)
print(s1.upper())
>> 실행결과
how to set a good goal HOW TO SET A GOOD GOAL |
3.4 lower()
lower()을 사용하면 문자열 전체를 소문자로 변경할 수 있습니다.
s1 = "How To Set A Good Goal"
print(s1)
print(s1.lower())
>> 실행결과
How To Set A Good Goal how to set a good goal |
3.5 strip()
strip()을 사용하면 문자열 양쪽 공백을 제거할 수 있습니다.
만약 문자열 왼쪽의 공백만 제거하고 싶다면 lstrip(),
문자열 오른쪽의 공백만 제거하고 싶다면 rstrip()을 사용하면 됩니다.
s1 = " python "
print("-", s1, "-")
print("-", s1.strip(), "-")
print("-", s1.lstrip(), "-")
print("-", s1.rstrip(), "-")
>> 실행결과
- python - - python - - python - - python - |
'Programming > Python' 카테고리의 다른 글
[Python] 6. 튜플 - 정의, 리스트를 튜플로 변환(tuple()) (0) | 2021.12.29 |
---|---|
[Python] 5. 리스트 슬라이스, 복사 (0) | 2021.12.24 |
[Python] 4. 리스트 - append(), insert(), del, pop(), remove(), sort(), sorted(), reverse(), len() (0) | 2021.12.22 |
[Python] 2. 변수 (0) | 2021.12.10 |
[Python] 1. 화면 출력 - print() (0) | 2021.12.10 |