문자열이 있는데 "e"를 "x"로 한 번에 하나씩 대체하려고 합니다.
예를 들면
x = "three"
이런 게 있으면 아래처럼 결과가 나왔으면 합니다.
그리고 바꿀 문자가 3개 있으면
y = "threee"
결과는
이렇게 나왔으면 합니다.
해본 건 이렇게 해봤는데요.
x.replace("e", "x", 1)
'thrxe'
그러나 두 번째 문자열 "threx"를 리턴하는 게 안됩니다.
python
이렇게 해보세요.
x = "threee"
[f"{x[:i]}x{x[i+1:]}" for i in (i for i, e in enumerate(x) if e=='e')]
['thrxee', 'threxe', 'threex']
generator를 사용하여 문자열을 통해 순차적으로 e를 x로 바꿀 수 있습니다.
예를 들면
def replace(string, old, new):
l = len(old)
start = 0
while start != -1:
start = string.find(old, start + l)
if start != -1:
yield string[:start] + new + string[start + l:]
z = replace('threee', 'e', 'x')
for s in z:
print(s)
출력
thrxee
threxe
threex
© 2022 pinfo. All rights reserved.