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

2024-09-25 10:34:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

字符串是不可变的,所以我需要为列表中的每个单词创建一个新的字符串,并删除一个字符。在

^{pr2}$

Tags: theto函数字符串程序urldefreplace
1条回答
网友
1楼 · 发布于 2024-09-25 10:34:37

Python字符串是不可变的,但是它们有返回新字符串的方法

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

退货

^{pr2}$

可以通过将子字符串替换为空字符串来删除它:

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

退货

'example'

为了强调方法是如何工作的,它们是内置于字符串对象中的函数。它们也可用作类方法:

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

相关问题 更多 >