简体   繁体   中英

Replace, for loops, format, and count the replacements in Python list

I need help editing my code so the output ends up like this:

Enter target word: red

Enter replacement word: pink

Number of replacements: 3

Original list:

blue, red, yellow, green, red, black, white, gray, blue, blue, red

List with replacement:

blue, pink, yellow, green, pink, black, white, gray, blue, blue, pink

Basically, I need to fix my code so that my original list and the replaced list use a for loop, but I also have to use the replace function, and at the same time I have to print the number of replacements (Which I don't know how to do).
Here's what my code looks like so far:

def replace (list1, target, replaceWord):
    new = ""
    for word in list1:
        if word == target:
            new += replaceWord + (", "[-1])
        else:
            new += word + (", "[-1])
    return new

def main():
    print ("Welcome! Enter your words one at a time and hit enter after each value.\nWhen you are done entering values, type stop.")
    inp = input ("Enter first value: ")
    list1 = []
    while inp !="stop":
        list1.append(inp)
        inp = input ("Enter first value: ")

    target = input ("Enter target word :")
    replaceWord =  input ("Enter replacement word: ")
    print()
    newlist = replace(list1,target,replaceWord)
    for i in newlist:
##     reps = ( )
##     reps += str (replaceWord)
    print ("Number of replacements: " +(reps))
    print ("Original list: " + (str (list1)))
    print ("List with replacement: " + newlist)

main()

Please help, thank you so much

def replace (list1, target, replaceWord):
    new = []
    replacements_no = 0
    for word in list1:
        if word == target:
            new.append(replaceWord)
            replacements_no += 1
        else:
            new.append(word)

    return new, replacements_no

def main():
    print ("Welcome! Enter your words one at a time and hit enter after each value.\nWhen you are done entering values, type stop.")
    inp = input ("Enter first value: ")
    list1 = []
    while inp !="stop":
        list1.append(inp)
        inp = input ("Enter first value: ")

    target = input("Enter targe word :")
    replaceWord = input("Enter replacement word: ")
    print()
    newlist, replacements = replace(list1,target,replaceWord)
    print("Number of replacements: {}".format(replacements))
    print ("Original list: " + (str (list1)))
    print ("List with replacement: {}".format(', '.join(newlist)))

main()

something like this should work. you do not have to stick together words in replace function, you can build new list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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