Python - concatenate a string to include a single backslash [duplicate] - python

This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Closed 7 months ago.
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 ?

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.

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'

Related

How do I change a singular element of a python list to a string [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 10 months ago.
Say I have a python list with 5 elements; list = ['a','b','c','d','e']. And I want to change it into 5 different strings so that each element is its own string, for example,
str1 = a str2 = b str3 = c str4 = d str5 = e
How would that be done?
Note: I would want it to be done autonomously if possible as the number of elements in a list is variable according to the data that is input at the beginning of the original code.
list_ = ['a','b','c','d','e']
You can use something called list unpacking, that you can do this way:
a, b, c, d, e = list_
As #Mark told you in the comments...
I'd be curious to know when str1, str2, etc. is preferable to s[1] , s[2]. It sounds like you are about to make a mistake you will later regret.
...you should avoid this approach.
If you don't know the lenght, you should read this, which suggests you to use the * star operator...
first, second, *others, third, fourth = names
...until you have the whole list unpacked.
Since you don't want to write an hell of if/elif/else over the lenght, I would suggest you to use exec to create variables on fly, even if (like Mark said) it's a bad idea.
I really want you to get that this is a bad idea, but you can use unpacking for useful scopes, in this case I would suggest you to read this, this and the respective PEP.

Variable inside python format specifier [duplicate]

This question already has an answer here:
How to pad numbers with variable substitution for padding width in format or f string? [duplicate]
(1 answer)
Closed 7 months ago.
I am wondering whether I can add a variable inside the f string to specify the width of item to be printed.
For example:
print("{:>5}".format("cat"))
In the example how can I replace 5 with a variable that can change at runtime.
inside the f string
Be careful using the term "f string" -- you're talking about a format string whereas an f-string is a feature of the latest releases of Python and something different, but related:
animal = 'cat'
pad = 5
print(f"{animal:>{pad}}")
Otherwise, if you just want a format string without the f-string, then #JohnnyMopp's comment (+1) shows the correct syntax.
Here is how:
a = 5
print("{:>"f"{a}""}".format("cat"))
Output:
cat
You can also do that using str.rjust():
a = 5
print("cat".rjust(a))
Output:
cat

how to remove u' and ' from tuple [duplicate]

This question already has answers here:
Remove 'u' from a python list
(5 answers)
Closed 5 years ago.
i saw that this question already been asked but the solutions i saw didn't worked for me.
i have a python script with tuple list which i want to retrieve without the unicode char (u') and without any other chars (like < [] > or < ' >) so only the data will pass to parameter.
my code look like this -
sql_cursor = con.cursor()
cursor = con.cursor()
cursor.execute(get_alerted_ip)
Results = cursor.fetchall()
for row in Results:
ip_to_open.append(row)
print (row)
con.close()
the output is -
(u'172.1.1.124',)
and the wanted output should look like -
172.1.1.124
I have already tried to convert the tuple to list or string in order to use methods like replace but it's not working.
what am i doing wrong? please help.
Simply
row[0].encode("utf-8")
will return the ascii version of the string

How to add comma in print statement in Python [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I print variable and string on same line in Python? [duplicate]
(18 answers)
Closed 5 years ago.
I'm new to python and learning how to code.
I'm printing last element of my list and sum of the list as-
print list[-1],sum
But the output is separated by " " and not separated by ",".
Any idea how to separate it by comma?
I'm using Python 2.7
Include it in quotes, like this:
print str(list[-1]) + "," + str(sum)
Enclosing them in str() is unnecessary if list[-1] and sum are strings.
In general, symbols are interpreted as Python symbols (for example, names like sum are interpreted as variable or function names). So whenever you want to print anything as is, you need to enclose it in quotes, to tell Python to ignore its interpretation as a Python symbol. Hence print "sum" will print the word sum, rather than the value stored in a variable called sum.
You'll have to compose that together into a string. Depending on what version of Python you're using, you could either do:
print "{},{}".format(list[-1], sum)
or
print "%s,%s" % (list[-1], sum)
If you were using Python3.6+, there would be a third option:
print(f"{list[-1]},{sum}")
Use the sep keyword argument:
print(list[-1], sum, sep=',')
You can use str.format() and pass whatever variables you want to get it formatted, for example:
x = 1
z = [1, 2, 3]
y = 'hello'
print '{},{},{}'.format(x, z[-1], y)
# prints: 1,3,hello

Python print list of sets without brackets [duplicate]

This question already has answers here:
Removing set identifier when printing sets in Python
(5 answers)
Closed 9 years ago.
I have a list of sets (using Python).
Is there a way to print this without the "set([])" stuff around it and just output the actual values they are holding?
Right now I'm getting somthing like this for each item in the list
set(['blah', 'blahh' blahhh')]
And I want it to look more like this
blah,blahh,blahhh
Lots of ways, but the one that occurred to me first is:
s = set([0,1])
", ".join(str(e) for e in s)
Convert everything in the set to a string, and join them together with commas. Obviously your preference for display may vary, but you can happily pass this to print. Should work in python 2 and python 3.
For list of sets:
l = [{0,1}, {2,3}]
for s in l:
print(", ".join(str(e) for e in s))
I'm assuming you want a string representation of the elements in your set. In that case, this should work:
s = set([1,2,3])
print " ".join(str(x) for x in s)
However, this is dependent on the elements of s having a __str__ method, so keep that in mind when printing out elements in your set.
Assuming that your list of sets is called set_list, you can use the following code
for s in set_list:
print ', '.join(str(item) for item in s)
If set_list is equal to [{1,2,3}, {4,5,6}], then the output will be
1, 2, 3
4, 5, 6

Categories