The modification code that i wan is:

When:
m = "i wan do something"

i need a modification code when get m result...

the code will automatic modify it become:

"i\\ wan do \\something"

Dani AI

Generated

wanted backslashes added into the string; showed a quick replace-based approach. Two important clarifications before changing text: (1) there are two different results people often mean — a backslash immediately before each space (e.g. i\ wan\ do\ something, useful for escaping spaces) or a backslash between words with no space (e.g. i\wan\do\something) — and (2) the interactive REPL shows doubled backslashes because it displays the string's representation (see repr), not the printed text.

If the intent is to place a backslash immediately before every space (escape the spaces), a regex insertion works well:

import re

s = "i wan do something"
out = re.sub(r' ', r'\\ ', s)
print(out)

If the intent is to join words with backslashes (no spaces), split-and-join is concise:

s = "i wan do something"
out = '\\'.join(s.split())
print(out)

Note: when inspecting results in code, use print() to see the actual characters; the representation shown by the REPL will escape backslashes for display. For shell-escaping or building command arguments, prefer tools designed for that task (see shlex.quote) rather than ad-hoc insertion of backslashes. For reference on the regex function used above, see re.sub.

Recommended Answers

All 2 Replies

i wan add "\\" for the result...

>>> mystring = 'I have a t on my keyboard'
>>> mystring.replace(' ', ' \\')
'I \\have \\a \\t \\on \\my \\keyboard'
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.