簡體   English   中英

替換/刪除字符串中的字符

[英]Replace/remove a character in a string

我查了一下並確實找到了一些幫助,但遺憾的是它們都使用了一個名為replace()的函數,這個函數在我必須使用的程序中不存在。

def getWordList(minLength, maxLength):
    url = "http://wordlist.ca/list.txt"
    flink = urllib2.urlopen(url)
    # where the new code needs to be to strip away the extra symbol
    for eachline in flink:
        if minLength+2<= len(eachline) <=maxLength+2:
            WordList.append(eachline.strip())
    return(WordList)

字符串是不可變的,所以我需要為列表中的每個單詞創建一個新字符串,並刪除一個字符。

initialWordList = []
WordList = []
jj = 0
def getWordList(minLength, maxLength):
    url = "http://cs.umanitoba.ca/~comp1012/2of12inf.txt"
    flink = urllib2.urlopen(url)
    for eachline in flink:
        if minLength+2<= len(eachline) <=maxLength+2:
            initialWordList.append(eachline.strip())
    while jj<=len(initialWordList)-1:
        something something something replace '%' with ''
        WordList.append(initialWordList[jj])
        jj+=1
return(WordList)

Python字符串是不可變的,但它們確實有返回新字符串的方法

'for example'.replace('for', 'an')

回報

'an example'

您可以通過將其替換為空字符串來刪除子字符串:

'for example'.replace('for ', '')

回報

'example'

為了強調方法的工作原理,它們是內置於字符串對象的函數。 它們也可以作為classmethods使用:

str.replace('for example', 'for ', '')

回報

'example'

所以如果你有一個字符串列表:

list_of_strings = ['for example', 'another example']

你可以用for循環替換它們中的子串:

for my_string in list_of_strings:
    print(my_string.replace('example', 'instance'))

打印出來:

for instance
another instance

由於字符串是不可變的,因此列表實際上不會更改(打印並查看),但您可以使用列表解析創建新列表:

new_list = [my_s.replace('example', 'instance') for my_s in list_of_strings]
print(new_list)

打印:

['for instance', 'another instance']

暫無
暫無

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

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