I am doing a python project, its a review maker kind using a sample string and replacing the symbol in the same line of the multistring then printing it with (check mark) next to the same text in the string as user input , I have a problem in replacing a certain symbol (☑) with the same line of string which equal to user input. Here is a code example to get the idea:
import string import re #this is a review maker with check boxes Graphics = """ ☐ You forget what reality is, ☐ Beautiful, ☐ Good, ☐ Decent, ☐ Bad, ☐ Don't look too long at it, ☐ MS-DOS """ def findAndReplace(Graphics): find_symbol = re.search(symbol = "☐") new_symbol =re.replace(symbol1 = "☑") return new_symbol # ask question to the user and replace symbol to same answer of the user. print = "Choose an answer each question to write the review" # the strings down is equal to the Graphics strings print = " Beautiful - Good - Decent - Bad" #control flow user_input1 = input("what do you think about Graphics? ") if user_input1 in Graphics: findAndReplace(Graphics) print(Graphics) else: print("we still have errors -")
Advertisement
Answer
You might be looking for something on the lines of :
# -*- coding: utf-8 -*- import string import re #this is a review maker with check boxes Graphics = """ ☐ You forget what reality is, ☐ Beautiful, ☐ Good, ☐ Decent, ☐ Bad, ☐ Don't look too long at it, ☐ MS-DOS """ def findAndReplace(line, line_num): replacement_string = re.sub("☐", "☑", line) mylist[line_num] = replacement_string return "n".join(mylist) # ask question to the user and replace symbol to same answer of the user. print( "Choose an answer each question to write the review") # the strings down is equal to the Graphics strings print(" Beautiful - Good - Decent - Bad") #control flow mylist = Graphics.split('n') user_input1 = input("what do you think about Graphics? ") for i, line in enumerate(mylist): try: if user_input1 in line: Graphics = findAndReplace(line, i) print(Graphics) except: print("we still have errors -")
Another perhaps better method leveraging regular expressions is:
#!/usr/bin/env python # -*- coding: utf-8 -*- import string import re #this is a review maker with check boxes Graphics = """ ☐ You forget what reality is, ☐ Beautiful, ☐ Good, ☐ Decent, ☐ Bad, ☐ Don't look too long at it, ☐ MS-DOS """ # ask question to the user and replace symbol to same answer of the user. print( "Choose an answer each question to write the review") # the strings down is equal to the Graphics strings print(" Beautiful - Good - Decent - Bad") #control flow user_input1 = input("what do you think about Graphics? ") try: result = re.search(user_input1, Graphics) first = Graphics[:result.start()] last = Graphics[result.start():] start = first.rfind("☐") new_string = first[:start] + first[start:].replace("☐", "☑") Graphics = new_string + last print(Graphics) except: print("we still have errors -")