Shubham
Shubham

Reputation: 11

Python adding extra backslash in list

The issue is when we pass the list to subprocess.Popen command. Normally python removes the extra slash but not in case of subprocess.Popen.

I have created a list in python and adding a variable.

var1='--username=domain\username'
ls=[]
ls.append(var1)
print(ls)

output:

['--username=domain\\username']

i don't want this extra backslash in the list because when i am passing list to the subprocess.Popen module, it is having problem reading the username.

Upvotes: 1

Views: 989

Answers (1)

bey
bey

Reputation: 74

The extra backslash is appearing because the code is setting the variable equal to a string literal. It's an escape character for that slash used in how it's represented.

https://www.geeksforgeeks.org/str-vs-repr-in-python/

The following code might help in understanding what's going on in your example:

var1='--username=domain\username'
ls=[]
ls.append(var1)
print(ls)
print(ls[0]) # the contents of the string literal
print(ls[0][16])
print(ls[0][17]) # only one slash after all
print(ls[0][18])

Upvotes: 1

Related Questions