Why doesn't this decode function working in python2? - python

I am debugging a python2 code:
tag_list = [convert(tag) for tag in tag_list]
print('tag_list: ', str(tag_list).decode("utf-8"))
However, the print out is like below:
u"['\\xe4\\xba\\xa4\\xe9\\x80\\x9a\\xe6\\x9c\\x8d\\xe5\\x8a\\xa1', '\\xe7\\xa4\\xbe\\xe4\\xbc\\x9a', '\\xe7\\x94\\xb5\\xe8\\xa7\\x86\\xe5\\x89\\xa7', '\\xe9\\x9f\\xb3\\xe4\\xb9\\x90']"
How to correctly print out the actual strings, instead of those x codes?

print("[" + ", ".join(tag_list) + "]")
I guess would give you the output you want ... maybe

Related

Python - newline if variable is in print function, need fix [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 1 year ago.
I have one problem with print in Python, I am starting to learn Python, but when I want to print variables in print function, it looks like that after one variable it adds newline to the outcome:
print(game_name + " | " + rating)
I am making a game database with my own ratings on the games but if it prints the game and the rating there is like one empty line belpw the game_name and rating is written, how can I delete that empty newline? I am very new to this, so please don't be mean...
Welcome to Stack Overflow! The most likely culprit is that there is a newline at the end of the game_name variable. The easy fix for this is to strip it off like this:
print(game_name.strip() + " | " + rating)
Say we had two variables like this.
game_name = 'hello\n'
rating = 'there'
game_name has the newline. To get rid of that use strip().
print(game_name.strip() + " | " + rating)
output
hello | there
If you want to remove the line break after printing, you can define the optional end parameter to the print statement.
print('Hello World', end='') # No new line
If your variable has a new line added to it, and you want to remove it, use the .strip() method on the variable.
print('Hello World\n'.strip()) # No empty line
For your code, you could run it:
print(game_name + " | " + rating, end='')
Or
print(game_name + " | " + rating.strip())
If the error is that a new line is printed after game_name, you'll want to call the strip method on that instead.
print(game_name.strip() + " | " + rating)
rating or game_name most likely have a new line after the specified string.
You can fix it by doing this:
game_name = game_name.strip('\n')
rating = rating.strip('\n')
print(game_name + " | " + rating)

Python 3 save string with hex escape codes as jpg

How can I save string s got in this way:
f = open("a.jpg", "rb")
b = f.read()
s = str(b)[2:-1]
as .jpg file? In other program I have only s like form of this image, so it is: "\\xff\\xd8\\xff\\xe0...".
My recommendation would be to change the code, that creates the string in this strange way.
If not possible:
Where is this string coming from? Is this a trusted source or is it coming from a web server or a person who might want to hack / break your computer?
Is the string really created with str(b)[2:-1] or is this just an approximation of the real problem?
I am asking, as this is making things a little more complicated then necessary. (It requires adding a try / except)
Following code should work:
from ast import literal_eval
def stripped_str_b_to_bytes(s):
try:
return literal_eval("b'" + s + "'")
except SyntaxError:
return literal_eval('b"' + s + '"')
testvalues = [
b"A'B",
b'A"B',
bytes([v for v in range(256)]),
]
for b in testvalues:
print("testing with ", b)
s = b[2:-1]
print("S =", s)
c = stripped_str_b_to_bytes(s)
assert b == c
It tries to prepend b' and append ' to s and evaluate that string as a python expression.
If this doesn't work, then it tries to prepend b" and append " to s and evaluate it.

Python - How to handle space as a value of a variable without quotes?

I have a string "bitrate:8000"
I need to convert it to "-bps 8000". Note that the parameter name is changed and so is the delimiter from ':' to space.
Also the delimiters are not fixed always, sometimes I would need to change from ':' to '-' using the same program.
The change rules are supplied as a config file which I am reading through the ConfigParser module. Something like:
[params]
modify_param_name = bitrate/bps
modify_delimiter = :/' '
value = 8000
In my program:
orig_param = modify_param_name.split('/')[0]
new_param = modify_param_name.split('/')[1]
orig_delimiter = modify_delimiter.split('/')[0]
new_delimiter = modify_delimiter.split('/')[1]
new_param_string = new_param + new_delimiter + value
However, this results in the string as below:
-bps' '8000
The question is how can I handle spaces without the ' ' quotes?
The reason why you're getting the ' ' string is probably related to the way you parse your modify_delimiter value.
You're reading that as a string, so that modify_delimiter == ":/' '".
When you're doing:
new_delimiter = modify_delimiter.split('/')[1]
Essentially modify_delimiter.split('/') gives you an array of [':', "' '"].
So when you're doing new_param_string = new_param + new_delimiter + value
, you are concatenating together 'bps' + "' '" + '8000'.
If your modify_delimiter contained the string ':/ ', this would work just fine:
>>> new_param_string = new_param + new_delimiter + value
>>> new_param_string
'bps 8000'
It has been pointed out that you're using ConfigParser. Unfortunatelly, I don't see an option for ConfigParser (either in python 2 or 3) to preserve trailing whitespaces - it looks like they're always stripped.
What I can suggest in that case is that you wrap your string in quotes entirely in your config file:
[params]
modify_param_name = bitrate/bps
modify_delimiter = ":/ "
And in your code, when you initialize modify_delimiter, strip the " on your own:
modify_delimiter = config.get('params', 'modify_delimiter').strip('"')
That way the trailing space will get preserved and you should get your desired output.

Syntax error when trying to print complex output

Can anyone please help me to rectify that syntax in python. Output is given as following:
ip='180.211.134.66'
port='123'
print ({"http":"http://"+ip +":"+ port +"})"
I would like to get output like this:
({"http":"http://180.211.134.66:123"})
Try to use str.format for this:
ip='180.211.134.66'
port='123'
data = {"http":"http://{0}:{1}".format(ip, port)}
print '({0})'.format(data)
In one line:
print "({0})".format({"http": "http://{0}:{1}".format(ip, port)})
The last two double quotes are unnecessary. remove them and you have :
ip='180.211.134.66'
port='123'
data = { 'http' : 'http://' + ip + ':' + port }
print str(data)
# output like this ({"http":"http://180.211.134.66:123"})
Assuming you want the whole output as string...
You should either use single quotes to contain the string or escape the double quotes.
Use this:
ip='180.211.134.66'
port='123'
print '({"http":"http://' + ip + ':' + port + '"})'
OR
print "({\"http\":\"http://" + ip + ":" + port + "\"})"
Output:
({"http":"http://180.211.134.66:123"})

How to append two strings in Python?

I have done this operation millions of times, just using the + operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the command-line it doesn't!
The list is:
["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&\r", "DUM'&\r"]
I want to discard the first and the last elements, the code is:
ediMsg = ""
count = 1
print "extract_the_info, lineList ",lineList
print "extract_the_info, len(lineList) ",len(lineList)
while (count < (len(lineList)-1)):
temp = ""
# ediMsg = ediMsg+str(lineList[count])
# print "Count "+str(count)+" ediMsg ",ediMsg
print "line value : ",lineList[count]
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ",ediMsg
count += 1
print "count ",count
Look at the output:
extract_the_info, lineList ["UNH+1+XYZ:08:2:1A+%CONVID%'&\r", "ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&\r", "DUM'&\r"]
extract_the_info, len(lineList) 8
line value : ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
ediMsg : ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
count 2
line value : DUM'&
DUM'& : ORG+1A+77499505:ABC+++A+FR:EUR++123+1A'&
count 3
Why is it doing so!?
While the two answers are correct (use " ".join()), your problem (besides very ugly python code) is this:
Your strings end in "\r", which is a carriage return. Everything is fine, but when you print to the console, "\r" will make printing continue from the start of the same line, hence overwrite what was written on that line so far.
You should use the following and forget about this nightmare:
''.join(list_of_strings)
The problem is not with the concatenation of the strings (although that could use some cleaning up), but in your printing. The \r in your string has a special meaning and will overwrite previously printed strings.
Use repr(), as such:
...
print "line value : ", repr(lineList[count])
temp = lineList[count]
ediMsg += " "+temp
print "ediMsg : ", repr(ediMsg)
...
to print out your result, that will make sure any special characters doesn't mess up the output.
'\r' is the carriage return character. When you're printing out a string, a '\r' will cause the next characters to go at the start of the line.
Change this:
print "ediMsg : ",ediMsg
to:
print "ediMsg : ",repr(ediMsg)
and you will see the embedded \r values.
And while your code works, please change it to the one-liner:
ediMsg = ' '.join(lineList[1:-1])
Your problem is printing, and it is not string manipulation. Try using '\n' as last char instead of '\r' in each string in:
lineList = [
"UNH+1+TCCARQ:08:2:1A+%CONVID%'&\r",
"ORG+1A+77499505:PARAF0103+++A+FR:EUR++11730788+1A'&\r",
"DUM'&\r",
"FPT+CC::::::::N'&\r",
"CCD+CA:5132839000000027:0450'&\r",
"CPY+++AF'&\r",
"MON+712:1.00:EUR'&\r",
"UNT+8+1'\r"
]
I just gave it a quick look. It seems your problem arises when you are printing the text. I haven't done such things for a long time, but probably you only get the last line when you print. If you check the actual variable, I'm sure you'll find that the value is correct.
By last line, I'm talking about the \r you got in the text strings.

Categories

Resources