2015-10-20 89 views
0

對於我的任務之一,我必須用一個字符串替換另一個我選擇的字符的令牌字符。呵呵,不過替換()是不是一種選擇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 

上述內容,目的是檢查字符串中的每個字母都與令牌字符相匹配,如果有,則用新字母替換。

我不知道我需要補充什麼,或者我做錯了什麼。

回答

2

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

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

如果您有old_char出現了多次,你可以重複,直到他們完成所有操作,或者把這個變成一個功能和復發的字符串後面的部分。

3

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

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來加入沒有分隔符的表達式(實際上是空字符串分隔符)。

便箋:你實際上不能改變字符串,這就是爲什麼所有的解決方案都必須構造一個新的字符串。

1

您可以迭代每個字符並替換您的令牌字符。你可以通過建立一個字符串,這樣做:

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, "$", "!")) 
0
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 
0

使用正則表達式:

import re 

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

這導致:

boobar 
0

一襯墊,如果你知道翻譯(中)和string.maketrans()

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