Python:有没有简单的方法来替换字符串,而不是替换()

问题描述:

对于我的任务之一,我必须用一个字符串替换另一个我选择的字符的令牌字符。呵呵,不过替换()是不是一种选择Python:有没有简单的方法来替换字符串,而不是替换()

我是新来的这一点,所以请不要我撕成碎片吧太难了:)

def myReplace(content,token,new): 
content = list(content) 
newContent = [] 
newContent = list(newContent) 
for item in content: 
    if item == token: 
     item = '' 
     newContent[item].append[new] 
return newContent 

上述内容,目的是检查字符串中的每个字母都与令牌字符相匹配,如果有,则用新字母替换。

我不知道我需要补充什么,或者我做错了什么。

查找索引字符()。 连接正面,新字符和背面。

pos = str.index(old_char) 
newStr = str[:pos] + new_char + str[pos+1:] 

如果您有old_char出现了多次,你可以重复,直到他们完成所有操作,或者把这个变成一个功能和复发的字符串后面的部分。

好吧,既然字符串是可迭代的,你可以这样做:

def my_replace(original, old, new): 
    return "".join(x if not x == old else new for x in original) 

例子:

>>> my_replace("reutsharabani", "r", "7") 
'7eutsha7abani' 

说明:这将使用generator expression发出新的角色,每当遇到旧符,并使用str.join来加入没有分隔符的表达式(实际上是空字符串分隔符)。

便笺:你实际上不能改变字符串,这就是为什么所有的解决方案都必须构造一个新的字符串。

您可以迭代每个字符并替换您的令牌字符。你可以通过建立一个字符串,这样做:

token = "$" 
repl = "!" 
s = "Hello, world$" 

new_s = "" 

for ch in s: 
    if ch == token: 
     new_s += repl 
    else: 
     new_s += ch 

或使用发电机str.join

def replacech(s, token, repl): 
    for ch in s: 
     if ch == token: 
      yield repl 
     else: 
      yield ch 

s = "Hello, World$" 
new_s = ''.join(replacech(s, "$", "!")) 

def repl(st,token,new): 
    ind = st.index(token) 
    st = st[:ind] + new +st[ind + len(new):] 
    return st 

print(repl("anaconda","co","bo")) 

anabonda 

使用正则表达式:

import re 

token = '-' 
str = 'foo-bar' 
new_str = re.sub(token, '', str) 

这导致:

boobar 

一衬垫,如果你知道翻译(中)和string.maketrans()

def myReplace(content, token, new): 
    # Note: assumes token and new are single-character strings 
    return content.translate(string.maketrans(token, new))