Home > Software engineering >  perform a split on a string with special characters
perform a split on a string with special characters

Time:09-10

I have a problem when trying to convert a string containing special characters to a list using a split. For example:

t="machine, machine\c&"

p=t.split(",")
print(p)

return:

['machine', ' machine\\c&']

I need the return conver only one \

['machine', ' machine\c&']

I have tried to use a replace but it does not work

CodePudding user response:

The backslash is only once there

When you print as

print(p)

you get list to string representation where the list looks like you have typed it in your code. The backslash should be escaped. Python knows that there is no combination like \c so allows not escaped variant.

If you print real values of the list, you get as it is:

print(' | '.join(p))

machine |  machine\c&

or char by char:

print(p[1][7], p[1][8], p[1][9])

e \ c

CodePudding user response:

Sorry, but my real intention is to create a json file

t="machine,machine\c&"

p=t.split(",")

host = {}
host['name'] = p[0]
host['filespace'] = p[1]

with open('json_host.json', 'w') as file:
    json.dump(host, file, indent=4)

The return code is:

{
    "name": "machine",
    "filespace": "machine\\c&"
}

I need this json with a one \

{
    "name": "machine",
    "filespace": "machine\c&"
}
  • Related