출처: Built-in Types — Python 3.12.1 documentation
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
문제:
문자열 처리 함수중 하나인 replace()를 활용하여,
첫행의 두번째 '날좀보소' 만 '고마워요' 로 변경하시오.
"""
# text 출처: https://ko.wikipedia.org/wiki/%EB%B0%80%EC%96%91%EC%95%84%EB%A6%AC%EB%9E%91
text = """\
날좀보소 날좀보소 날좀보소
동지섣달 꽃본듯이 날좀보소
아리아리랑 쓰리쓰리랑 아라리가 났네
아리랑 고개로 넘어간다
"""
lines = text.split("\n")
lines[0] = lines[0][:4] + \
lines[0][4:].replace("날좀보소", "고마워요", 1)
text = "\n".join(lines)
print(text)
# 편집: Emacs 26.2 (Ubuntu 18.04)
# 마지막 갱신: 2019년 7월 11일
(bionic)soyeomul@localhost:~/test$ ./1.py
날좀보소 고마워요 날좀보소
동지섣달 꽃본듯이 날좀보소
아리아리랑 쓰리쓰리랑 아라리가 났네
아리랑 고개로 넘어간다
(bionic)soyeomul@localhost:~/test$
[ibus-hangul(서라운딩 패치판)에서 작성했씁니다]
[quote=“str.replace(old, new[, count])”]
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
[/quote]
끝에 옵션 숫자는 치환을 몇번 반복할 것인가를 정의합니다.
1 ===> 1회
2 ===> 2회
3 ===> 3회
…
옵션을 **생략 **하면 조건에 맞는 문자열을 모두다 찾아서 치환합니다. 기본값 .
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
str = "날좀보소 날좀보소 날좀보소"
str = str.replace("날좀보소", "고마워요")
print(repr(str)) # '고마워요 고마워요 고마워요'
[ibus-hangul(서라운딩 패치판)에서 작성했습니다]
replace() 없이 순수한 방식으로 시도하려합니다.
(bionic)soyeomul@localhost:~/test$ cat 3.py
#!/usr/bin/env python3
-- coding: utf-8 - -
str = “날좀보소”
str[1] = “쫌”
print(repr(str))
(bionic)soyeomul@localhost:~/test$ ./3.py
Traceback (most recent call last):
File “./3.py”, line 5, in
str[1] = “쫌”
TypeError : ‘str’ object does not support item assignment
(bionic)soyeomul@localhost:~/test$
(bionic)soyeomul@localhost:~/test$ cat 3.py
#!/usr/bin/env python3
-- coding: utf-8 - -
str = “날좀보소”
str_split = list(str)
str_split[1] = “쫌”
str = “”.join(str_split)
print(repr(str))
(bionic)soyeomul@localhost:~/test$ ./3.py
‘날쫌 보소’
(bionic)soyeomul@localhost:~/test$
replace() 함수와 비교하려 추가로 적어봤어요,
순수한 방식으로는 [str → list] 자료형 변경을 한 연후에 치환이 가능한 반면,
replace() 함수는 문자열 자료형 (str) 상태에서 바로 치환이 이루어집니다 .
이게 너무 감사하네요^^^;;;
[ibus-hangul(서라운딩 패치판)에서 작성했습니다]
혹시 찾으시는 분들을 위하야 소스코드 링크 남깁니다.
소스코드(str.replace): https://github.com/python/cpython/blob/master/Objects/stringlib/replace.h
[ibus-hangul(서라운딩 패치판)에서 작성했씁니다]
좀 더 복잡한 치환은 정규표현식(re) 모듈을 쓰시면 됩니다.
한글로 자세하게 친절한 예제까지 듬뿍 있기에 그대로 링크를 남깁니다.
re.sub 해설판 (한글): https://greeksharifa.github.io/%EC%A0%95%EA%B7%9C%ED%91%9C%ED%98%84%EC%8B%9D(re)/2018/08/04/regex-usage-05-intermediate/#%EC%A0%95%EA%B7%9C%ED%91%9C%ED%98%84%EC%8B%9D-%EC%A4%91%EA%B8%89-%EC%B9%98%ED%99%98
re.sub 공식문서 (영어): https://docs.python.org/3/library/re.html#re.sub
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
str = "날좀보소"
str = re.sub("좀.", "쫌주", str) # '.' ===> 일치되는 모든 한(one) 글자(character)
print(repr(str)) # '날쫌주소'
[ibus-hangul(서라운딩 패치판)에서 작성했습니다]
추가정보입니다.
다음 글도 참고적으로 봐주시면 도움이 될거 같아요. 스택오브플로우의 심각한 토론글입니다.
대략 요약하자면,
과거엔 MutableString(변형 가능한 문자열) 자료형이라는것이 존재했었는데,
최근 파이썬3에선 완전히 제거되었다 라는게 핵심인거 같아요.
답변자는 대체제로 str.replace , str.format 그리고 re.sub 등을 사용하길 권유하였습니다.
– 2011년 1월 10일, Rosh Oxymoron
[ibus-hangul(서라운딩 패치판)에서 작성했씁니다]
파이썬3 정규표현식으로 IPv6 주소를 추출해봤습니다.
소스코드(파이썬3): https://gitlab.com/soyeomul/test/raw/master/161875.py
이것으로 파이썬 문자열 치환을 갈무리합니다. 감사합니다^^^
소여물 황병희 드림
[ibus-hangul(서라운딩 패치판)에서 작성했습니다]