str.join(iterable)
str.join(iterable)
는 반복 가능한 모든 항목을 가져와 하나의 문자열로 결합한다.
구분 기호로 문자열을 지정해야 한다.
# 리스트를 문자열로 연결
words = ["Hello", "world", "from", "Python"]
sentence = " ".join(words)
print(sentence) # Hello world from Python
# 다른 구분자 사용
csv = ",".join(["Alice", "Bob", "Charlie"])
print(csv) # Alice,Bob,Charlie
# 딕셔너리를 문자열로 연결
myDict = {"name": "John", "country": "Norway"}
mySeparator = "TEST"
x = mySeparator.join(myDict)
print(x) # nameTESTcountry
str.split(separator, maxsplit)
str.split(eparator, maxsplit)
은 문자열을 list
로 나눈다. 구분 기호를 지정할 수 있으며, 기본 구분 기호는 공백이다.
# 기본 사용
sentence = "Hello world from Python"
words = sentence.split()
print(words) # ['Hello', 'world', 'from', 'Python']
# 구분자를 지정한 사용
csv = "Alice,Bob,Charlie"
names = csv.split(",")
print(names) # ['Alice', 'Bob', 'Charlie']
str.strip(characters)
str.strip(characters)
메서드는 문자열의 시작과 끝에서 공백(또는 지정한 문자)를 제거한다.
# 기본 사용
text = " Hello, world! "
cleaned_text = text.strip()
print(cleaned_text) # Hello, world!
# 특정 문자 제거
text = "***Hello, world!***"
cleaned_text = text.strip("*")
print(cleaned_text) # Hello, world!
str.replace(oldvalue, newvalue, count)
str.replace(oldvalue, newvalue, count)
메서드는 문자열 내의 지정된 구문을 다른 지정된 구문으로 바꾼다.
oldvalue
: 필수. 검색할 문자열newvalue
: 필수. 이전 값을 바꿀 문자열count
: 선택 사항. 바꿀 이전 값의 발생 횟수를 지정하는 숫자. 기본값은 모든 발생.text = "Hello world"
new_text = text.replace("world", "Python")
print(new_text) # Hello Python
str.find(value, start, end)
str.find(value, start, end)
메서드는 문자열 내에서 특정 문자열을 찾고, 처음 발견된 위치의 인덱스를 반환한다. 해당 문자열을 찾지 못하면 -1
을 반환한다.
index()
와 비슷하지만 index()
는 값을 발견하지 못하면 예외를 발생시킨다.
value
: 필수. 검색할 값.start
: 선택 사항. 검색을 시작할 위치. 기본값은 0.end
: 선택 사항. 검색을 끝낼 위치. 기본값은 문자열 끝.text = "Hello world"
index = text.find("world")
print(index) # 6
index = text.find("Python")
print(index) # -1
str.rfind(value, start, end)
str.rfind(value, start, end)
메서드는 문자열 내에서 특정 문자열을 찾고, 마지막으로 발견된 위치의 인덱스를 반환한다. 해당 문자열을 찾지 못하면 -1
을 반환한다.
rindex()
와 거의 비슷하다.
value
: 필수. 검색할 값.start
: 선택 사항. 검색을 시작할 위치. 기본값은 0.end
: 선택 사항. 검색을 끝낼 위치. 기본값은 문자열 끝.text = "Hello world, welcome to the world"
index = text.rfind("world")
print(index) # 22
str.startswith(value, start, end)
str.startswith(value, start, end)
메서드는 문자열이 지정된 문자열로 시작하면 True
를 반환하고, 그렇지 않으면 False
를 반환한다.
value
: 필수. 문자열이 다음으로 시작하는지 확인할 값.start
: 선택 사항. 검색을 시작할 위치를 지정하는 정수.end
: 선택 사항. 검색을 끝낼 위치를 지정하는 정수.text = "Hello world"
print(text.startswith("Hello")) # True
print(text.startswith("world")) # False
str.endswith(value, start, end)
str.endswith(value, start, end)
메서드는 문자열이 지정된 문자열로 끝하면 True
를 반환하고, 그렇지 않으면 False
를 반환한다.
value
: 필수. 문자열이 다음으로 끝나는지 확인할 값.start
: 선택 사항. 검색을 시작할 위치를 지정하는 정수.end
: 선택 사항. 검색을 끝낼 위치를 지정하는 정수.text = "Hello world"
print(text.endswith("world")) # True
print(text.endswith("Hello")) # False
str.upper()
str.upper()
메서드는 문자열을 모두 대문자로 변환한다.
text = "Hello world"
print(text.upper()) # HELLO WORLD
str.lower()
str.lower()
메서드는 문자열을 모두 소문자로 변환한다.
text = "Hello World"
print(text.lower()) # hello world
str.title()
str.title()
메서드는 문자열을 타이틀 케이스로 변환한다. 각 단어의 첫 글자를 대문자로 바꾼다. 단어에 숫자나 기호가 포함되어 있을 경우, 그 다음의 첫 글자가 대문자로 변환된다.
text = "hello world"
print(text.title()) # Hello World
str.splitlines(keeplinebreaks)
str.splitlines(keeplinebreaks)
메서드는 문자열을 줄 단위로 나누어 리스트로 반환한다. 각 줄의 끝에 있는 줄바꿈 문자는 제거된다.
keeplinebreaks
: 선택 사항. 줄 바꿈을 포함할지(True
) 또는 포함하지 않을지(False
) 지정하며, 기본값은 False
.text = """Hello world
This is a test
Goodbye world"""
lines = text.splitlines()
print(lines) # ['Hello world', 'This is a test', 'Goodbye world']
str.zfill(len)
str.zfill(len)
메서드는 문자열의 왼쪽에 0을 추가하여 문자열의 길이를 지정된 길이로 만든다. 숫자 문자열에 주로 사용된다. len
매개변수의 값이 문자열의 길이보다 작으면 채우기가 수행되지 않는다.
len
: 필수. 원하는 문자열 길이를 지정하는 숫자.number = "42"
print(number.zfill(5)) # 00042