0

So, I need to be able to duplicate a certain character in a string the user inputs, for example:

Input: I\ love\ bac\kslashes\
Output: I\\ love\\ bac\\kslashes\\

This is as far as I have, it doesn't help that I'm duplicating backslashes, the escape character... How would I go about doing this?

Mave
  • 81
  • 1
  • 1
  • 9
  • In addition to a bad `for` loop syntax, your second quotation mark after `for` is quoted by the backslash before and counts as part of the now left open string. – Klaus D. Jan 09 '20 at 08:16
  • Why do you need to do that? What is the string used for? I suspect this is an instance of the XY problem. – mkrieger1 Jan 09 '20 at 08:20
  • @mkrieger1 Specifying the webdriver path in a selenium automation script. On windows, paths use backslashes instead of forwardslashes ;( – Mave Jan 09 '20 at 08:23

3 Answers3

2

You can do this with str.replace():

userinput = input('Input your backslashed phrase')
replaceWith = '/'
newString = userinput.replace(replaceWith, replaceWith*2)
print(newString)
Ladi Oyeleye
  • 154
  • 4
1

For every \ you need another \ to escape it. When you insert the input Python does it for you, so userinput is actually already 'I\\ love\\ bac\\kslashes\\', but prints I\ love\ bac\kslashes\. You can replace the double '\\' with '\\\\'

userinput = input('Input your backslashed phrase')
userinput = userinput.replace('\\', '\\\\')
print(userinput) # I\\ love\\ bac\\kslashes\\
Guy
  • 46,488
  • 10
  • 44
  • 88
0

the line

for '\' in listeduserinput:

is a fundamental misunderstanding of the for loop. it's not searching for matches, it's looping through each item and binding a name to that item for your use inside the loop.

there are other ways to accomplish the kind of thing you had in mind, but to use a for loop to do this, you would want to do:

output = ''
for character in listeduserinput:
    if character == '\':
         output += '\\'
    else:
         output += character
Personman
  • 2,324
  • 1
  • 16
  • 27
  • Isn't it better to dump the for-loop entirely? – Cedric Jan 09 '20 at 08:17
  • Thank you for the feedback! I knew something was going on with the for loop. I've used it before, but this is only my 3rd real script. Thanks for the help. – Mave Jan 09 '20 at 08:20
  • 1
    @Cedced_Bro if this were production code, sure. but what's going on here is learning, and telling this person to replace the loop entirely won't help them fix their understanding of for loops – Personman Jan 09 '20 at 08:20
  • @Samuurai if this answer helped you solve your problem, please click the check mark by it so that others know the question has been answered. – Personman Jan 09 '20 at 08:21
  • @Personman I marked someone else's answer as correct since their method worked better in my case, but I just wanted to thank you for pointing out my misunderstanding of the For loop. – Mave Jan 09 '20 at 08:54