0

In python how to search and replace in strings?

This is my code, I want to replace 'python' with 'Java'

#!/usr/bin/env python3
    
find_it = "python"
repl_it = "Java"
text = "python is amazing. I love python, it is the best language. python is the most readable language."
    
if text.find(find_it):
    text = text.replace(find_it, repl_it)
    
print(text)

The output is still the same:

python is amazing. I love python, it is the best language. python is the most readable language.

How to replace words in a string?

10 Rep
  • 2,217
  • 7
  • 19
  • 33
Kumar Prasad
  • 13
  • 1
  • 2
  • 1
    ``text.find(find_it)`` returns the *position* of the search string, which in this case is 0 – aka boolean False. – MisterMiyagi Oct 08 '20 at 18:15
  • Does this answer your question: [https://stackoverflow.com/a/9189193/11915595](https://stackoverflow.com/a/9189193/11915595)? – Jorge Morgado Oct 08 '20 at 18:17
  • 2
    @JorgeMorgado these are not duplicates. OP does reassign the call of `replace`. The problem is that it is not being called to begin with. – DeepSpace Oct 08 '20 at 18:18

2 Answers2

4

str.find returns the index of the beginning of the first match.

In your case, it is 0, so the if condition will be evaluated as False hence .replace is not being called (if you will remove python from the start of the string your code will work).

You don't need the check at all. str.replace will not raise an error if it does not find what to replace.

find_it = "python"
repl_it = "Java"
text = "python is amazing. I love python, it is the best language. python is the most readable language."
text = text.replace(find_it, repl_it)
print(text)
# Java is amazing. I love Java, it is the best language. Java is the most readable language.
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Oh! OK. But how do I find if the word exists in a string? I only want to replace it if I find it in a string, else I want to keep the original string as it is. – Kumar Prasad Oct 08 '20 at 18:29
  • 1
    @KumarPrasad Again, if the string you are replacing is not in the string, the string will not be modified. You don't need to worry about it – DeepSpace Oct 08 '20 at 18:30
  • @KumarPrasad To find a substring in a string you can use `if find_it in text:`. – Matthias Oct 08 '20 at 18:55
0

You have your code wrapped in the conditional if text.find(find_it) The problem with that is that returns the first index of the text you are looking for. Which in your case is 0 as your text starts with python. Your conditional is retunring 0 and then evaluating to false. The find method does not return a boolean if text was found but an index of where it was

find_it = "python"
repl_it = "Java"
text = "python is amazing. I love python, it is the best language. python is the most readable language."


text = text.replace(find_it, repl_it)

print(text)

This code works just fine

Josh Zwiebel
  • 883
  • 1
  • 9
  • 30