Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - concatenate a string to include a single backslash

Tags:

python

In Python 2.6, I need to create a string by concatenating INTRANET\ and a userid such as jDoe to obtain a string INTRANET\jDoe. This will string will be a part of a SQL query. I have tried this a number of ways but end up getting INTRANET\\jDoe and hence my query does not return any results.

I want to do this:

a = 'INTRANET\\'
b = 'jDoe'
c = a+b   ### want to get c as 'INTRANET\jDoe', not 'INTRANET\\jDoe'

Thanks


The problem seems a little different:

When I print c, I get 'INTRANET\jDoe'. But when I append c to a list (to be used in a sql query) as below:

list1 = []
list1.append(c)
print list1

>>>['INTRANET\\jDoe']

Why is this ?

like image 798
sunny Avatar asked Oct 22 '22 09:10

sunny


2 Answers

The additional \ is there due to python escaping.

>>> print 'INTERNET\\jDoe'
INTERNET\jDoe

It doesn't affect the SQL you are using. You should look at another direction.

like image 167
Yossi Avatar answered Oct 24 '22 09:10

Yossi


Try the following code,

s1 = "INTRANET"
s1 = s1 + "\\"
s1 = s1 + "jDoe"
print s1

This will give the correct output INTERNET\jDoe

If you simply try to view the content of the variable you will see an extra \, which is an escape sequence in python. In that case it will show,

'INTERNET\\jDoe'
like image 22
Deepu Avatar answered Oct 24 '22 11:10

Deepu