반응형
파이썬에서는 문자열을 출력하고 조작하기 위한 다양한 함수와 키워드들이 있어요. 이 문서에서는 문자열을 효과적으로 다루기 위해 꼭 알아야 할 10가지 핵심 개념을 정리합니다.
🔹 1. sep - print 함수에서 값 사이 구분자 지정
print("Python", "is", "fun", sep="-")
👉 출력: Python-is-fun
print("2025", "03", "31", sep="/")
👉 출력: 2025/03/31
🔹 2. end - 출력 후 줄 끝 지정
print("Hello", end=" ♥ ")
print("World")
👉 출력: Hello ♥ World
for i in range(3):
print(i, end=", ")
👉 출력: 0, 1, 2,
🔹 3. join() - 리스트를 문자열로 합치기
date = ["2025", "03", "31"]
print("-".join(date))
👉 출력: 2025-03-31
words = ["I", "love", "Python"]
print(" ".join(words))
👉 출력: I love Python
🔹 4. split() - 문자열을 리스트로 나누기
s = "apple,banana,grape"
print(s.split(","))
👉 출력: ['apple', 'banana', 'grape']
sentence = "Hello world Python"
print(sentence.split())
👉 출력: ['Hello', 'world', 'Python']
🔹 5. format() - 문자열에 값 삽입
text = "My name is {} and I am {} years old."
print(text.format("Alice", 25))
👉 출력: My name is Alice and I am 25 years old.
print("{} * {} = {}".format(3, 4, 3*4))
👉 출력: 3 * 4 = 12
🔹 6. f-string - 문자열에 변수 바로 넣기
name = "Bob"
age = 30
print(f"My name is {name}, and I'm {age} years old.")
👉 출력: My name is Bob, and I'm 30 years old.
x, y = 7, 8
print(f"{x} + {y} = {x + y}")
👉 출력: 7 + 8 = 15
🔹 7. replace() - 문자열 일부 변경
text = "I like Java"
print(text.replace("Java", "Python"))
👉 출력: I like Python
message = "hello hello"
print(message.replace("hello", "hi", 1))
👉 출력: hi hello
🔹 8. strip(), lstrip(), rstrip() - 공백 제거
text = " hello "
print(text.strip()) # 'hello'
print(text.lstrip()) # 'hello '
print(text.rstrip()) # ' hello'
text2 = "***Python***"
print(text2.strip("*")) # 'Python'
🔹 9. upper(), lower(), capitalize() - 대소문자 변환
word = "python"
print(word.upper()) # 'PYTHON'
print(word.lower()) # 'python'
print(word.capitalize()) # 'Python'
text = "hELLo WoRLd"
print(text.capitalize()) # 'Hello world'
🔹 10. find(), index() - 특정 문자열 위치 찾기
text = "hello world"
print(text.find("world")) # 6
print(text.index("world")) # 6
text2 = "banana"
print(text2.find("na")) # 2
print(text2.find("x")) # -1
✅ 요약표
개념 주요 기능 예시
sep | print에서 값 사이 구분자 | print(a, b, sep='-') |
end | print 끝에 붙는 문자 | print(a, end='♥') |
join() | 리스트 → 문자열 | '-'.join(list) |
split() | 문자열 → 리스트 | 'a,b'.split(',') |
format() | 문자열에 값 삽입 | 'Hi {}'.format(name) |
f-string | 문자열에 변수 삽입 | f"Hi {name}" |
replace() | 문자열 일부 변경 | s.replace('a', 'b') |
strip() 등 | 공백 제거 | s.strip() |
upper() 등 | 대소문자 변환 | s.upper() |
find() 등 | 문자열 위치 찾기 | s.find('hi') |
🔸 여러 개념을 함께 사용하는 예시
예제 1: 사용자 입력 처리 (공백 제거 + 대문자 변환)
user_input = " apple "
word = user_input.strip().upper()
print(f"입력한 단어: {word}")
👉 출력: 입력한 단어: APPLE
예제 2: 문자열 나누고 출력 형식 바꾸기
text = "dog,cat,bird"
animals = text.split(",")
print("동물들:", " | ".join(animals))
👉 출력: 동물들: dog | cat | bird
예제 3: 데이터 포맷과 출력 꾸미기
name = "alice"
age = 28
print("이름: {} / 나이: {}세".format(name.capitalize(), age))
👉 출력: 이름: Alice / 나이: 28세
예제 4: 줄마다 출력 (end 사용)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit, end=" | ")
👉 출력: apple | banana | cherry |
예제 5: strip과 capitalize로 이름 처리
name = " alice "
clean_name = name.strip().capitalize()
print(f"Hello, {clean_name}!")
👉 출력: "Hello, Alice!"
이 개념들은 문자열 출력과 조작의 기초이자 핵심이에요. 다양한 함수들을 적절히 조합하면 출력 형식을 자유롭게 제어하고, 문자열 데이터를 쉽게 다룰 수 있어요.
반응형
'IT > Python Basic' 카테고리의 다른 글
[Python] 특집 - 십진수와 이진수 변환 (0) | 2025.03.21 |
---|---|
[Python] 특집 - lambda 함수 활용법 (0) | 2025.03.19 |
[python] 파이썬 isdigit() 함수 완벽 가이드 (0) | 2025.03.19 |
[Python] 특집 - range() 함수로 리스트 다루기 (0) | 2025.03.18 |
[Python] 초급 개념21 - 파이썬 반복문의 종류 (0) | 2025.03.18 |
[Python] 초급 개념21 - sort()와 sorted() (0) | 2025.03.14 |
[Python] 튜플, 딕셔너리, 집합 개념 정리 특집 (0) | 2025.02.28 |
[python] 문자와 ASCII/Unicode 변환 - ord()와 chr() 함수 정리 (0) | 2025.02.27 |
댓글