Advertisement
Guest User

Untitled

a guest
Aug 19th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | None | 0 0
  1. def removechar():
  2.     """2) Write a method which will remove any given character from a String? (solution)
  3.    hint : you can remove a given character from String by converting it into character array and then using substring() method for removing them from output string."""
  4.     print('This is a snippet of code to erase a character from a string, first, enter your sentence')
  5.     print('What are the characters?')
  6.     string = input()
  7.     lst = list(string)
  8.     print('What is the character you would like to remove?')
  9.     char = input()
  10.     while char not in lst:
  11.         print("This character is not in your word/sentence, try again")
  12.         char = input()
  13.     indexnum = lst.index(char) #grab the index of the character from char input
  14.     lstx = lst[:indexnum] + lst[indexnum+1:] #variable for new list excluding character that was removed from char
  15.     newlst = ''.join(lstx) #joins back together the list from variable lstx
  16.     if string.count(char) == 1:
  17.         print(newlst)
  18.     if string.count(char) > 1:
  19.         print(char + ' ' + 'appears more than once, which occurrence would you like to delete?')
  20.         if char in lst:
  21.             print('Which instance of', char, 'should be deleted?') #need to check/write at each position
  22.             print(string)
  23.             print(list(range(len(string)))) #prints the character index
  24.             enumer = ([pos for pos, i in enumerate(string) if i == char]) #finds the locations (in number) of char
  25.             print(enumer)
  26.             whichnum = int(input())
  27.             if int(whichnum) in enumer:
  28.                 numdel = string[:whichnum] + string[whichnum+1:]
  29.                 print(numdel)
  30.                 return numdel
  31.             else:
  32.                 print("Please try again, incorrect number given")
  33.  
  34.     return reloop()
  35.  
  36.  
  37. def reloop():
  38.     while True:
  39.         again = input("Would you like to remove another character? Please enter 'yes' or 'no'")
  40.         if again == 'no':
  41.             return
  42.         elif again == 'yes':
  43.             removechar()
  44.         else:
  45.             if again not in 'yes' or 'no': #used if so pycharm would stop bothering me about incorrect syntax
  46.                 print("Please try again incorrect input")
  47.  
  48.  
  49. removechar()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement