Bob Unger
Bob Unger

Reputation: 341

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.

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)

Upvotes: 2

Views: 6053

Answers (1)

Aaron Hall
Aaron Hall

Reputation: 395075

Python strings are immutable, but they do have methods that return new strings

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

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

Upvotes: 4

Related Questions