설명을 위한 웹 코딩환경 https://tio.run/#python3
Try It Online
tio.run
https://pythontutor.com/python-compiler.html#mode=edit
Python compiler - visualize, debug, get AI help from ChatGPT
Write code in Python 3.11 [newest version, latest features not tested yet] Python 3.6 [reliable stable version, select 3.11 for newest] Python 2.7 [unsupported] ------ Java C (C17 + GNU extensions) C++ (C++20 + GNU extensions) JavaScript (ES6) Visualize Ex
pythontutor.com
파이썬의 문자열(String) 자료형은 텍스트 데이터를 다룰 때 사용하는 기본적인 자료형
단일 문자 또는 문자들의 시퀀스(sequence)를 저장할 수 있다.
문자열은 불변(immutable) 자료형으로, 생성된 후에는 그 내용을 변경할 수 없다.
파이썬에서 문자열을 사용하는 방법과 문자열과 관련된 다양한 메서드들을 설명한다.
1. 문자열 생성 및 기본 사용법
파이썬에서 문자열은 작은따옴표('
)나 큰따옴표("
)로 감싸서 생성할 수 있다.
# 문자열 생성
string1 = "Python, BOJ"
print(string1)
print("-"*20)
string2 = 'Python, BOJ'
print(string2)
파이썬에서는 여러 줄의 문자열을 사용할 때는 삼중 따옴표('''
또는 """
)를 사용한다.
# 여러 줄의 문자열
string = """Python,
BOJ"""
print(string)
string = '''Python,
BOJ'''
print(string)
string = "Python,\nBOJ"
print(string)
string = 'Python,\nBOJ'
print(string)
2. 문자열 인덱싱과 슬라이싱
문자열은 시퀀스 자료형이므로 리스트처럼 인덱싱과 슬라이싱이 가능하다. 인덱스는 0부터 시작하며, 음수 인덱스를 사용하면 문자열의 끝에서부터 역으로 접근할 수 있다.
sample_str = "Hello, Python!"
# 인덱싱
print(sample_str[0]) # 출력: H
print(sample_str[-1]) # 출력: !
# 슬라이싱
print(sample_str[0:5]) # 출력: Hello
print(sample_str[7:]) # 출력: Python!
print(sample_str[:5]) # 출력: Hello
print(sample_str[::2]) # 출력: Hlo yhn
🤔연습문제: 백준27866 문자와 문자열 -인덱싱
🤔연습문제: 백준9086 문자열 -인덱싱
* 길이를 알기 위해서는 len()함수를 쓸 수 있다.
s = "Life is short (You need Python)"
print(len(s))
🤔연습문제: 백준2743단어 길이 재기
* 아스키 코드(ASCII)코드를 다루는 방법은 간단하다. 주로 두 가지 작업이 많이 사용되는데, 하나는 문자를 아스키 코드로 변환하는 것이고, 다른 하나는 아스키 코드를 문자로 변환하는 것이다.
- 문자를 아스키 코드로 변환하기:
ord()
함수를 사용하여 문자를 아스키 코드로 변환할 수 있다. char = 'A' ascii_code = ord(char) print(ascii_code) # 출력: 65
- 아스키 코드를 문자로 변환하기:
chr()
함수를 사용하여 아스키 코드를 문자로 변환할 수 있다. ascii_code = 65 char = chr(ascii_code) print(char) # 출력: 'A'
🤔연습문제: 백준 11654아스키 코드
3. 문자열의 불변성
문자열은 불변(immutable) 자료형이기 때문에, 한 번 생성된 문자열은 변경할 수 없다. 만약 문자열의 일부를 수정하고 싶다면, 새로운 문자열을 만들어야 한다.
# 문자열의 일부를 변경하려고 하면 오류가 발생함
# sample_str[0] = 'h' # TypeError 발생
# 대신 새로운 문자열을 생성해야 함
new_str = 'h' + sample_str[1:]
print(new_str) # 출력: hello, Python!
4. 문자열 연결 및 반복
파이썬에서는 문자열을 +
연산자로 연결할 수 있으며, *
연산자로 반복할 수 있다.
# 문자열 연결
greeting = "Hello" + " " + "World"
print(greeting) # 출력: Hello World
# 문자열 반복
repeated_str = "Python! " * 3
print(repeated_str) # 출력: Python! Python! Python!
5. 문자열 메서드
파이썬은 문자열을 다루기 위한 다양한 내장 메서드를 제공한다. 이 중에서 자주 사용되는 몇 가지 메서드를 소개한다.
lower()
와 upper()
문자열을 모두 소문자 또는 대문자로 변환한다.
text = "Hello, Python!"
print(text.lower()) # 출력: hello, python!
print(text.upper()) # 출력: HELLO, PYTHON!
strip()
, lstrip()
, rstrip()
문자열의 앞뒤에서 특정 문자를 제거한다. 아무 인자를 전달하지 않으면 공백을 제거한다.
text = " Hello, Python! "
print(text.strip()) # 출력: "Hello, Python!"
print(text.lstrip()) # 출력: "Hello, Python! "
print(text.rstrip()) # 출력: " Hello, Python!"
replace()
문자열 내에서 특정 문자열을 다른 문자열로 대체한다.
text = "Hello, Python!"
new_text = text.replace("Python", "World")
print(new_text) # 출력: Hello, World!
split()
과 join()
split()
메서드는 문자열을 특정 구분자를 기준으로 나누어 리스트로 반환하며, join()
메서드는 리스트의 문자열 요소들을 하나의 문자열로 결합한다.
text = "Python is fun"
words = text.split() # 공백을 기준으로 분리
print(words) # 출력: ['Python', 'is', 'fun']
# 리스트의 문자열 요소들을 결합
joined_text = " ".join(words)
print(joined_text) # 출력: Python is fun
🤔연습문제: 백준2902 KMP는 왜 KMP일까?
find()
와 index()
find()
는 특정 문자가 처음 나타나는 위치의 인덱스를 반환하며, 해당 문자가 없을 경우 -1을 반환한다. index()
는 같은 역할을 하지만, 문자가 없을 경우 ValueError
를 발생시킨다.
text = "Hello, Python!"
print(text.find("Python")) # 출력: 7
print(text.find("Java")) # 출력: -1
# print(text.index("Java")) # ValueError 발생
startswith()
와 endswith()
문자열이 특정 문자로 시작하거나 끝나는지를 확인하여 True
또는 False
를 반환한다.
text = "Hello, Python!"
print(text.startswith("Hello")) # 출력: True
print(text.endswith("!")) # 출력: True
6. 포맷팅 및 f-string
파이썬에서는 문자열 내에 변수를 삽입할 수 있는 방법으로 포맷팅을 제공한다. 이를 통해 가독성 높은 코드를 작성할 수 있다.
%
연산자
기본적인 문자열 포맷팅 방법으로, %
연산자를 사용한다.
name = "Alice"
age = 25
text = "My name is %s and I am %d years old." % (name, age)
print(text) # 출력: My name is Alice and I am 25 years old.
str.format()
메서드
보다 유연한 포맷팅 방법으로, 중괄호 {}
를 사용하여 변수의 위치를 지정한다.
text = "My name is {} and I am {} years old.".format(name, age)
print(text) # 출력: My name is Alice and I am 25 years old.
f-string (Python 3.6 이상)
가장 현대적인 포맷팅 방법으로, 문자열 앞에 f
를 붙이고 중괄호 {}
안에 변수를 넣어 사용한다.
text = f"My name is {name} and I am {age} years old."
print(text) # 출력: My name is Alice and I am 25 years old.
02-2 문자열 자료형
문자열(string)이란 연속된 문자들의 나열을 말한다. 예를 들면 다음과 같다. ```plaintext Life is too short, You need Python a…
wikidocs.net
https://youtu.be/j06b2RdJB-s?list=PLMsa_0kAjjrcxiSJnHNfzBN71D3zpYtkX
https://youtu.be/V0dZucvVwho?list=PLMsa_0kAjjrcxiSJnHNfzBN71D3zpYtkX
https://youtu.be/QqOgNyZ16R0?list=PLMsa_0kAjjrcxiSJnHNfzBN71D3zpYtkX
https://youtu.be/jCSEElJDixk?list=PLMsa_0kAjjrcxiSJnHNfzBN71D3zpYtkX
https://docs.python.org/ko/3/library/stdtypes.html
Built-in Types
The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some colle...
docs.python.org