-3

I have a python line that has

/c/hossam/fawzy/

this sentence

I want to replace all the forward slashes whenever they are found in a line, I am really wanting to use the replace method. so here is what I've done.. and I've reached the point when I print "Yeah Found" whenever I see it in the for loop, but can't figure out how to replace it.

import sys


file = open(r"E:\AutomationTestPath\t2.py", 'r+')
contents = file.read()

ListContents = list(contents)

print(ListContents)

SearchingFor = '/'

for letter in ListContents:
    if SearchingFor in letter:
        print("Yeah Found")
  • You can use the string's `replace` function or the `replace` method from the regex module. It's a very common task with a lot of possible solutions. https://stackoverflow.com/questions/1228299/changing-one-character-in-a-string or https://stackoverflow.com/questions/44780952/regex-end-of-line-and-specific-chracters/44781398#44781398 – Dschoni Feb 24 '21 at 07:34

2 Answers2

1

Try:

import re
sentence = "/c/hossam/fawzy/"
sentence = re.sub(r"/", r"-", sentence)  # Replace '/' with '-'
print(sentence)

Output:

-c-hossam-fawzy-
Sakurai
  • 106
  • 6
  • Using a regular expression is overkill here. A simple `sentence = sentence.replace('/', '-')` is enough. – Matthias Feb 24 '21 at 09:18
0
import re
file = open(r"E:\AutomationTestPath\t2.py", 'r+') #Opening The FIle
contents = file.read()
Sentence = str(contents) #Converting to String

sentence = re.sub(r"/", r"-", Sentence)
print(sentence)