替换/删除字符串中的字符

时间:2014-03-02 18:56:27

标签: python list if-statement

我查了一下并确实找到了一些帮助,但遗憾的是他们都使用了一个名为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)

1 个答案:

答案 0 :(得分:3)

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']