簡體   English   中英

Python:如何用索引替換字符串

[英]Python:how to replace string by index

我正在編寫像unix tr這樣的程序,可以替換輸入字符串。 我的策略是首先查找源字符串的所有索引,然后用目標字符串替換它們。 我不知道如何用索引替換字符串,所以我只使用切片。 但是,如果目標字符串的長度不等於源字符串,則此程序將出錯。 我想知道用索引替換字符串的方法是什么。

def tr(srcstr,dststr,string):
    indexes = list(find_all(string,srcstr)) #find all src indexes as list
    for index in indexes:
        string = string[:index]+dststr+string[index+len(srcstr):]
    print string

TR( 'AA', '毫米', 'aabbccaa')
結果是正確的:mmbbccmm
但如果tr('aa','ooo','aabbccaa'),輸出將是錯誤的:

ooobbcoooa

Python字符串是不可變的(據我所記得),因此您不能只是插入內容。

幸運的是,Python已經有了一個replace()函數。

>>> s = "hello, world!"
>>> s1 = s.replace("l", "k")
>>> print s1
hekko, workd!

您知道str.replace方法嗎? 我認為它會做你想要的:

http://docs.python.org/library/string.html#string.replace

而且,當您發現除了要支持簡單的字符串替換之外,還希望支持更多內容時,請查看re模塊:

http://docs.python.org/library/re.html

def tr(srctr, deststr, string):
    string = string.split(srctr)
    return ''.join([deststr if i == '' else i for i in string ])

print tr('aa', 'ooo', 'aabbccaa') # ooobbccooo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM