본문 바로가기
파이썬/파이썬 기초

[파이썬 Python] 문자열 str (결합, 검색, 치환, 분할, 길이)

by SMCon 2023. 8. 11.
728x90
반응형

오늘은 파이썬 (python)의 문자열 str과 관련된 결합, 검색, 치환, 분할, 길이 등의 연산에 대해서 알아보겠습니다.

 

1. 문자열 생성과 출력:

문자열은 작은 따옴표(') 또는 큰 따옴표(")로 둘러싸여 있는 텍스트입니다.

# 문자열 생성
message_single_quotes = '작은 따옴표로 생성된 문자열'
message_double_quotes = "큰 따옴표로 생성된 문자열"

# 문자열 출력
print(message_single_quotes)
print(message_double_quotes)

 

2. 문자열 결합:

두 개의 문자열을 결합할 때는 + 연산자를 사용합니다.

first_name = "John"
last_name = "Doe"

full_name = first_name + " " + last_name
print("결합된 이름:", full_name)

 

3. 문자열 포맷팅:

문자열 포맷팅을 사용하면 문자열 내에 변수 값을 삽입할 수 있습니다.

name = "Alice"
age = 30

# f-string 포맷팅
intro = f"제 이름은 {name}이고, 나이는 {age}살입니다."
print(intro)

 

4. 문자열 길이:

len() 함수를 사용하여 문자열의 길이를 확인할 수 있습니다.

text = "Hello, World!"

length = len(text)
print("문자열 길이:", length)

 

5. 문자열 분할과 결합:

split() 함수를 사용하여 문자열을 분할하거나, join() 함수를 사용하여 리스트를 문자열로 결합할 수 있습니다.

sentence = "This is an example sentence."

words = sentence.split()  # 공백을 기준으로 분할
print("분할된 단어들:", words)

reconstructed_sentence = " ".join(words)  # 공백으로 결합
print("다시 결합된 문장:", reconstructed_sentence)

 

6. 문자열 검색과 치환:

find() 함수를 사용하여 문자열 내에서 특정 문자열을 검색하거나, replace() 함수를 사용하여 문자열을 치환할 수 있습니다.

text = "Python is fun and Python is powerful."

search_term = "Python"
position = text.find(search_term)
print(f"'{search_term}'의 위치:", position)

new_text = text.replace("Python", "Java")
print("치환된 문장:", new_text)
728x90
반응형