简体   繁体   English

在字符串中逐个字符地进行处理,并与python交换空格

[英]Going character by character in a string and swapping whitespaces with python

Okay so I have to switch ' ' to *s. 好的,所以我必须将''切换为* s。 I came up with the following 我想出了以下几点

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)

Assigning len(ch) doesn't seem to work and also I'm pretty sure this isn't the most efficient way of doing this. 分配len(ch)似乎无效,而且我很确定这不是执行此操作的最有效方法。 The following is the output I'm aiming for: 以下是我的目标输出:

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

Are you looking for replace() ? 您在寻找replace()吗?

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

See a demo on ideone.com additionally. 另请参阅ideone.com上的演示

For your second requirement (to replace only from the 8th to the 12th character), you could do: 对于第二个要求(仅替换第8到第12个字符),您可以执行以下操作:

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

Assuming you have to do it character by character you could do it this way: 假设您必须逐个字符地执行此操作,则可以这样进行:

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

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

print replaced

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM