简体   繁体   English

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

[英]Replace/remove a character in a string

I looked it up and did find some help with this, but unfortunately they all use a function called replace(), which does not exist in the program I have to use. 我查了一下并确实找到了一些帮助,但遗憾的是它们都使用了一个名为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)

Strings are immutable, so i need to create a new string for each word in the list with removing a character. 字符串是不可变的,所以我需要为列表中的每个单词创建一个新字符串,并删除一个字符。

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 strings are immutable, but they do have methods that return new strings Python字符串是不可变的,但它们确实有返回新字符串的方法

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

returns 回报

'an example'

You can remove a substring by replacing it with an empty string: 您可以通过将其替换为空字符串来删除子字符串:

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

returns 回报

'example'

To emphasize how methods work, they are functions that are builtin to string objects. 为了强调方法的工作原理,它们是内置于字符串对象的函数。 They are also available as classmethods: 它们也可以作为classmethods使用:

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

returns 回报

'example'

So if you have a list of strings: 所以如果你有一个字符串列表:

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

you can replace substrings in them with a for loop: 你可以用for循环替换它们中的子串:

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

prints out: 打印出来:

for instance
another instance

Since strings are immutable, your list actually doesn't change (print it and see) but you can create a new list with a list comprehension: 由于字符串是不可变的,因此列表实际上不会更改(打印并查看),但您可以使用列表解析创建新列表:

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

prints: 打印:

['for instance', 'another instance']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM