개발일기 [Python 파이썬]

[Python join & split & replace] 파이썬 쪼개기 합치기

neullo 2024. 2. 21. 13:19

 

1. split() / string을 list로 변환하기

스플릿은 내가 원하는 문자를 기준으로 문자 열을 쪼갤 수 있다.

# split은 string.split("구분자")로 구성되어 있습니다.

string = "hello/python/world!!"
string_list = string.split("/") # split() 안에 들어간 값을 기준으로 문자를 나눈다.

print(string_list) # ['hello', 'python', 'world!!']

 

2. join() / list를 string으로 변환하기

반대로 조인을 이용해 쪼개진 문자를 합칠 수 있다.

# join은 "사이에 들어갈 문자".join(리스트) 로 구성되어 있습니다.

string_list = ["hello", "python", "world"]
string = "!! ".join(string_list)

print(string) # hello!! python!! world

 

3. replace() / 문자열 바꾸기

특정문자를 내가 원하는 문자로 바꿀 수 있다. 아래를 보면 before에는 이랬는데 after 에는 느낌표를 물결로 바꿔줘 하니 hello world!!! 가 hellow world~~~ 로 바뀌어 나온다.

# replace는 "변경할 문자".replace("변경 전 문자", "변경 후 문자")로 구성되어 있습니다.

before_string = "hello world!!!"
after_string = before_string.replace("!", "~") # !를 ~로 변경

print(after_string) # hello world~~~