0

I want this program ignore case letter E.g. for string 'Apple' either 'A' or 'a' can replace the 'A' in Apple with any other character.

store = []

def main(text=input("Enter String: ")):

  replace = input("Enter the replace char: ")
  replace_with = input("Enter the replace with char: ")

  for i in text:
    store.append(i)


main()
print(store)  # printing the result here

f_result = ''.join(store)  # Joining back to original state 
print(f_result)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Manish
  • 501
  • 4
  • 11

3 Answers3

1

Use the re standard library which has the sub method and an option to ignore case. It is also convenient to use. This works for your example:

import re

def main(text=input("Enter String: ")):

    replace = input("Enter the replace char: ")
    replace_with = input("Enter the replace with char: ")

    return re.sub(replace, replace_with, text, flags=re.IGNORECASE)

main()

>>Enter String: Apple
>>Enter the replace char: a
>>Enter the replace with char: B
>>'Bpple'
BernardL
  • 5,162
  • 7
  • 28
  • 47
  • yeah! I am new here and also new to python language. I was trying hard myself to write my own algorithm without using built -in function. – Manish Nov 16 '18 at 22:04
  • No problem, just remember to keep it as simple and usable :) You can do `import this` if you would want to learn the zen of Python. BTW just in cased you missed out on [what to do when someone answers](https://stackoverflow.com/help/someone-answers) – BernardL Nov 16 '18 at 22:08
0

Try using the ascii numbers. The difference between the code for an uppercase and it's respective lower case is 32

  • I tried and also searched the internet for the solution using ascii number but didn't get the answer. – Manish Nov 16 '18 at 22:06
0

There are multiple posts on Stack Overflow about case-insensitive string replacements in python, but almost all of them involve using regular expressions. (For example see this post.)

IMO, the simplest thing in this case would be to make 2 calls to str.replace. First replace the upper case version and then replace the lower case version.

Here is an example:

text = "Apple"
to_repl = "a"
repl_with = "B"
print(text.replace(to_repl.upper(), repl_with).replace(to_repl.lower(), repl_with))
#Bpple
pault
  • 41,343
  • 15
  • 107
  • 149
  • Thanks for the help ! I was thinking that is there any other way without using built-in function. Like writing our own algorithm to solve a specific problem without taking any help of built-in function. Still your answer appreciated! thanks:) – Manish Nov 16 '18 at 21:45
  • @ManishGupta seems like you want to avoid calling `str.replace` - you could do: `"".join([t if t not in [to_repl.lower(), to_repl.upper()] else repl_with for t in text])` – pault Nov 16 '18 at 22:00