2013-10-18 121 views
-2

我想寫一個程序來改變字符,如果ch被發現在名爲st的字符串中,我會用'!'替換它。如何替換字符串中的子字符串?

我寫了一個程序,但由於某些原因,如果我輸入驗證碼不能取代例如一個字母:「!」 ST =一個 CH =一個

我不得到的輸出相反,我得到'一個',但我不希望我想它是'!'

我的代碼是

st = raw_input("String: ") 
ch = raw_input("character: ") 


def replace_char(st,ch): 
    if st.find(ch): 
     new = st.replace(ch,'!') 
     print new 
     return new 
    elif len(st)==len(ch): 
     if ch==st: 
      print"!" 
     else: 
      print st 
    else: 
     print st 
     return st 

replace_char(st,ch) 

請幫助我不明白我在做什麼錯誤或從我的代碼

+1

使用合理的主題 - > Downvote。 –

+1

str.find()不返回True或False,它返回找到的字符串的索引。 –

+0

對不起,這是舊的,我改變它,但它仍然不會工作.... –

回答

3

缺少從Python文檔:

find(s, sub[, start[, end]])¶ 

Return the lowest index in s where the substring sub is found such 
that sub is wholly contained in s[start:end]. Return -1 on failure. 
Defaults for start and end and interpretation of negative values is 
the same as for slices. 

它沒有提到有關find()返回True或False的內容。這是你的問題。

對於字符串搜索更好的使用

if some_string in some_otherstring: 
    do_something() 
1

st.find(CH)返回位置CH是ST不是真/假。因爲if == True在Python中爲True,所以程序在某些情況下可以工作...... :) 考慮str =='a'和ch =='a',第一個條件失敗,但第二個條件僅在str和ch有效相同的長度。我想你的東西還有其他東西。 在我的電腦裏,你的程序工作,除非是在st中第一次搜索ch,如下所示:st ='afsdf'ch ='a'。 更好的辦法是像如下:

st.replace(ch, '!') 

這將適用於所有情況。

+0

Downvote重複我已經給出的答案。 –