python

[python] 파이썬 기본 (2) - 문자형

hail2y 2025. 4. 4. 13:07
  • 따옴표 가리지 않음 (큰 따옴표 안에 작은 따옴표 포함 가능, 반대도 가능)
  • print('Hello', 'World') # Hello World
  • 문자열 결합 시 + 연산자 사용
  • 문자열 반복 시 * 연산자 사용
  • 문자열 인덱싱, 슬라이싱 가능 text[::2], text[::-1]
  • 문자열 길이 확인 시 len()
  • upper(), lower(), capitalize()
  • find(sub): 특정 문자열의 시작 위치 반환 없으면 -1
  • count(sub): 특정 문자열 몇 번 등장하는지 반환
  • replace(before_text, after_text) 특정 부분 문자열을 다른 문자열로 교체
  • split(delim): 특정 구분자를 기준으로 문자열 나눔
  • join(iterable): 리스트 같은 반복 가능한 객체를 문자열로 결합
  • strip() = lstrip() + rstrip() 공백 제거
  • 문자열 포함 여부: in, not in
  • 문자열 포맷팅: "{}, {}".format(a, b), f'string'
a = "1"
b = 'easy'
print(type(b))  # <class 'str'>
print(a+b)      # 1easy

1 + '1' # 문자랑 숫자는 더할 수 없다. -> TypeError 발생
# 작은 따옴표와 큰 따옴표 모두 사용 가능
text1 = 'Hello'
text2 = "World"

# 따옴표 혼합 사용 - 큰 따옴표 안에 작은 따옴표 포함 가능
text3 = "It's a beautiful day"

print(text1, text2)  # Hello World
print(text3)         # It's a beautiful day
text = "Hello, Python!"
print(len(text))  # 14
print(text.capitalize())  # Hello world -- 맨 앞글자만
text = "hello world, hello Python"
print(text.find("world"))  # 6
print(text.find("Java"))   # -1 파이썬에서 -1: False를 의미
print(text.count("hello")) # 2

text = "I like Python Python"
new_text = text.replace("Python", "Java")
print(new_text)  # I like Java


# split 예제
text = "apple,banana,cherry"
fruits = text.split(",")  # 리스트로 반환
print(fruits)  # ['apple', 'banana', 'cherry']
print(type(fruits)) # <class 'list'>

# join 예제
fruits_list = ['apple', 'banana', 'cherry']
result = " ".join(fruits_list)
print(result)  # apple banana cherry

text = "Hello, Python"
print("Python" in text)     # True
print("Java" not in text)   # True
name = "hailey"
age = 20
message = "My name is {} and I am {} years old.".format(name, age, 'good') # {} 개수보다 많아도 개수만큼 지정
print(message)  # My name is hailey and I am 20 years old.

# f-string
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
print(message)  # My name is Alice and I am 25 years old.

 

 

https://colab.research.google.com/drive/18xkvuLnIq2vwRE88Kho8onQJIAQpp0Ek

 

Google Colab Notebook

Run, share, and edit Python notebooks

colab.research.google.com