在字符串中逐个字符并使用python

时间:2016-05-30 17:16:46

标签: python string whitespace

好的,所以我必须切换' '到* s。我想出了以下

def characterSwitch(ch,ca1,ca2,start = 0, end = len(ch)):
    while start < end:
        if ch[start] == ca1:
            ch[end] == ca2
        start = start + 1
sentence = "Ceci est une toute petite phrase."
print characterSwitch(sentence, ' ', '*')
print characterSwitch(sentence, ' ', '*', 8, 12)
print characterSwitch(sentence, ' ', '*', 12)
print characterSwitch(sentence, ' ', '*', end = 12)

分配len(ch)似乎不起作用,而且我非常确定这不是最有效的方法。以下是我的目标输出:

Ceci*est*une*toute*petite*phrase.
Ceci est*une*toute petite phrase.
Ceci est une*toute*petite*phrase.
Ceci*est*une*toute petite phrase.

2 个答案:

答案 0 :(得分:4)

您在寻找replace()吗?

sentence = "Ceci est une toute petite phrase."
sentence = sentence.replace(' ', '*')
print sentence
# Ceci*sest*sune*stoute*spetite*sphrase.

另请参阅a demo on ideone.com

对于你的第二个要求(只替换第8个字符到第12个字符),你可以这样做:

sentence = sentence[8:12].replace(' ', '*')

答案 1 :(得分:1)

假设你必须逐个字符地做,你可以这样做:

sentence = "this is a sentence."
replaced = ""

for c in sentence:
    if c == " ":
        replaced += "*"
    else:
        replaced += c

print replaced