[英]Python replacing string given a word
嗨,有誰知道如何制作一個函數,用給定單詞中的字符(無限重復)替換字符串中的每個字母字符。 如果一個字符不是字母,它應該保持原樣。 此外,這必須在不導入任何內容的情況下完成。
def replace_string(string,word)
'''
>>>replace_string('my name is','abc')
'ab cabc ab'
到目前為止,我想出了:
def replace_string(string,word):
new=''
for i in string:
if i.isalpha():
new=new+word
else: new=new+i
print(new)
但是,這個函數只打印 'abcabc abcabcabcabc abcabc' 而不是 'ab cabc ab'
更改如下:
def replace(string, word):
new, pos = '', 0
for c in string:
if c.isalpha():
new += word[pos%len(word)] # rotate through replacement string
pos += 1 # increment position in current word
else:
new += c
pos = 0 # reset position in current word
return new
>>> replace('my name is greg', 'hi')
'hi hihi hi hihi'
如果您不能使用itertools
模塊,首先創建一個生成器函數,它將無限期地循環您的替換詞:
def cycle(string):
while True:
for c in string:
yield c
然后,稍微調整一下現有的函數:
def replace_string(string,word):
new=''
repl = cycle(word)
for i in string:
if i.isalpha():
new = new + next(repl)
else:
new = new+i
return new
輸出:
>>> replace_string("Hello, I'm Greg, are you ok?", "hi")
"hihih, i'h ihih, ihi hih ih?"
另一種寫法(但我認為第一個版本更具可讀性,因此更好):
def replace_string(string,word):
return ''.join(next(cycle(word)) if c.isalpha() else c for c in string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.