I am currently working with JSON and Python and I have a problem.
When I write:
x = {}
x['red'] = {'name': "red"}
y = {}
y['red'] = {'p': 1}
z = x['red']['name'], y['red']['p']
print(z)
I get back:
('red', 1)
But I want it like:
red1
Without using
print(x['red']['name'], y['red']['p'])
Thanks for your help :)
When we resolve the variables in the line
z = x['red']['name'], y['red']['p']
we get this:
z = "red", 1
This is, in Python the same as writing:
z = ("red", 1)
This line defines a data-type called a "tuple". It is similar to a list. When you use print to write out the value of this variable, Python formats this as such and adds the parens.
If you want the string "red1" as output, you need to do some minor string processing. In your tuple, your first item is a string, the next is an integer. Those two are not directly concatenable in Python using +. You either need to convert (cast) the number first, or use a string formatting function:
Example 1 - Using str() to cast the number to string
z = x['red']['name'] + str(y['red']['p'])
Example 2 - Using simple string formatting
z = '%s%s' % (x['red']['name'], y['red']['p'])
Example 3 - Using f-strings
z = f"{x['red']['name']}{y['red']['p']}"
Just concatenate the string, easy:
z = y['red']['name'] + str(z['red']['p'])
print(z)
You need to call str() around z['red']['p'] because it's an integer. By converting it to a string, you can then concatenate the two strings into one string
When you type z = x['red']['name'], y['red']['p'] Python automatically takes it as tuple.
But you want this to be treated as string and get concatenated results.
for this you may use,
z = str(x['red']['name']) + str(y['red']['p'])
print(''.join(z)) does the trick.
Cheers
Demo: https://repl.it/repls/MinorRoyalTrace
Edit: use print(''.join(str(element) for element in z)) instead for handle str+ int
Related
I am new to Python, I am calling an external service and printing the data which is basically byte literal array.
results = q.sync('([] string 2#.z.d; `a`b)')
print(results)
[(b'2018.06.15', b'a') (b'2018.06.15', b'b')]
To Display it without the b, I am looping through the elements and decoding the elements but it messes up the whole structure.
for x in results:
for y in x:
print(y.decode())
2018.06.15
a
2018.06.15
b
Is there a way to covert the full byte literal array to string array (either of the following) or do I need to write a concatenate function to stitch it back?
('2018.06.15', 'a') ('2018.06.15', 'b')
(2018.06.15,a) (2018.06.15,b)
something like the following (though I want to avoid this approach )
for x in results:
s=""
for y in x:
s+="," +y.decode()
print(s)
,2018.06.15,a
,2018.06.15,b
Following the previous answer, your command should be as follows:
This code will result in a list of tuples.
[tuple(x.decode() for x in item) for item in result]
The following code will return tuples:
for item in result:
t = ()
for x in item:
t = t + (x.decode(),)
print(t)
You can do it in one line, which gives you back a list of decoded tuples.
[tuple(i.decode() for i in y) for x in result for y in x]
I have a program, which is returning strings like : b'\\xfe\\xff\\x000\\x008\\x00/\\x001\\x002\\x00/\\x001\\x009\\x009\\x003'
How can I convert this to a readable string. The value of this should be 08/12/1993
so imagine i have something like this
a = "b'\\xfe\\xff\\x000\\x008\\x00/\\x001\\x002\\x00/\\x001\\x009\\x009\\x003'"
print(a.convert())
The sequence \xfe\xff tells us we are having utf-16 (cf. http://unicodebook.readthedocs.io/guess_encoding.html)
Let us try:
x = b'\xfe\xff\x000\x008\x00/\x001\x002\x00/\x001\x009\x009\x003'
print(x.decode('utf-16'))
which gives
'08/12/1993'
For completeness:
If the input is given as a string you can use eval to turn it into <class 'bytes'>:
x = eval("b'\\xfe\\xff\\x000\\x008\\x00/\\x001\\x002\\x00/\\x001\\x009\\x009\\x003'")
print(x) ### b'\xfe\xff\x000\x008\x00/\x001\x002\x00/\x001\x009\x009\x003'
print(x.decode('utf-16')) ### returns 08/12/1993
def draw_constellation_file(file_name):
x = open(file_name)
y = x.read()
y = y.splitlines()
for i in range(0, len(y)):
a = y[i]
b = a.split(',')
aa = str(get_line_for_star_name(b[0]))
cc = get_star_point_from_line(aa)
return aa
get_star_point_from_line looks like this:
def get_star_point_from_line(stardata):
stardata = stardata.split(',')
x = float(stardata[0])
y = float(stardata[1])
return [x, y]
The output:
ValueError: could not convert string to float: None
Here's the thing: the stardata.split doesn't seem to split. I'm sure it has something to do with the None.
Any ideas?
You're passing aa = str(get_line_for_star_name(b[0]))
into get_star_point_from_line(stardata): and that shows you only passing 1 index: b[0].
If b[0] is not a full list and only one string than when you assign x = float(stardata[0])andy = float(stardata[1]) you are trying to assign those variables to indices that dont exist.
If b[0] is a full string it may be splitting up differently than what you thought it would. I would try splitting it using just split() instead of split(',') and then rstrip(',') to get rid of the commas.
Its difficult to pinpoint the problem without knowing what the list looks like when you originally did aa = str(get_line_for_star_name(b[0])). Which by the way is converting that into a string, which you then attempt to reconvert later into a float, which I thought was kind of odd.
It seems there is an error with this code
def get_star_point_from_line(stardata):
stardata = stardata.split(',')
x = float(stardata[0]) //passing string value in float will cause an error
y = float(stardata[1])
return [x, y]
I think the data from the parameter stardata has contained a string value.
in draw_constellation_file, you set b = a.split(',') and pass b[0] to get_line_for_star_name, b[0] will have no ',', so may be you can post the code for get_line_for_star_name to see the reason for the probelm
"None" tends to indicate that nothing is being passed into the function in question. You should make sure that the data you're passing in is what you expect it to be.
In this case, stardata[0] or stardata[1] might not exist. That being said, you need to check the line number to know which one is the problem.
I am very new to Python, and I'm trying to combine elements from two lists and produce a string from the combination.
My variables are:
fro = ['USD']
to = ['AUD', 'CAD', 'EUR']
I want output like this in a string:
pairs = "USDAUD,USDCAD,USDEUR"
Thanks a ton in advance for your help.
Why not use a generator expression like this:
fro = ['USD']
to = ['AUD', 'CAD', 'EUR']
pairs = ','.join(fro[0] + x for x in to)
Note that from is a reserved keyword and is thus not a valid variable name.
Output:
>>>pairs
'USDAUD,USDCAD,USDEUR'
If you were ever curious as to whether something you wish to use as a variable name is a keyword (and thus an illegal variable name) or not, you can always check with something like this:
>>> import keyword
>>> keyword.iskeyword("from")
True
Elizion's answer is nice and succinct, but as a beginner you may want to approach it without using an intermediate/advanced structure like a generator:
fro = ['USD']
to = ['AUD', 'CAD', 'EUR']
pairs = ""
for word in to:
pairs += fro[0] + word + ","
Removing the trailing comma:
pairs = pairs[:-1]
Elizion is absolutely correct.
If you have list elements varies dynamically, you can use this line:
absolutely pythonic way!!
pair_elem = ','.join('%s%s' % (x, y) for y in to for x in fro)
And conventional way is like, iterate list elems:
for multiple in to:
for single in fro:
pairs = ",".join(single + multiple)
I am getting an error here and I am wondering if any of you can see where I went wrong. I am pretty much a beginner in python and can not see where I went wrong.
temp = int(temp)^2/key
for i in range(0, len(str(temp))):
final = final + chr(int(temp[i]))
"temp" is made up of numbers. "key" is also made of numbers. Any help here?
First, you defined temp as an integer (also, in Python, ^ isn't the "power" symbol. You're probably looking for **):
temp = int(temp)^2/key
But then you treated it as a string:
chr(int(temp[i]))
^^^^^^^
Was there another string named temp? Or are you looking to extract the ith digit, which can be done like so:
str(temp)[i]
final = final + chr(int(temp[i]))
On that line temp is still a number, so use str(temp)[i]
EDIT
>>> temp = 100 #number
>>> str(temp)[0] #convert temp to string and access i-th element
'1'
>>> int(str(temp)[0]) #convert character to int
1
>>> chr(int(str(temp)[0]))
'\x01'
>>>