0

I would like to convert a string temp.filename.txt to temp\.filename\.txt using python

Tried string replace method but the output is not as expected

filename = "temp.filename.txt"
filename.replace(".", "\.")
output: 'temp\\.filename\\.txt'
4
  • I don't think replace modifies the string you call it on. Did you mean filename=filename.replace(".", "\.")? Commented Mar 10, 2021 at 5:58
  • In a string parameter "\\." means "\.", "'\\\." means "\\."so on and so forth. You don't need to worry that your output is a wrong direction. Commented Mar 10, 2021 at 5:58
  • 2
    The only reason this works in the first place is because \. isn't recognized as a special escape sequence. You should always double up \\ when using it in a string: filename.replace(".", "\\."). Commented Mar 10, 2021 at 6:00
  • or use r"" strings, but even these can trick you, e.g. if your string finishes with a \, you'll still need to double up that last \... Commented Mar 10, 2021 at 6:02

2 Answers 2

5

\ is a special character, which is represented as \\, this doesn't mean your string actually contains 2 \ characters.

(as suggested by @saipy, if you print your string, only single \ should show up...)

Sign up to request clarification or add additional context in comments.

Comments

0
filename = "temp.filename.txt"
result=filename.replace(".", "\.")
print(result)

I stored a result in variable(result) its working fine check this

2 Comments

@Julien, can you click on the link for image
@Julien answer is correct. It's just how you see the string. Actually I was doing the right thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.