Converting a list to string in python 2.7 - python

I have a list xline. It is initialized and then appended. But I am getting an error when I run?
xline = []
---#append
----
print (''.join(xline)) # Convert list into string
Run time error
print (''.join(xline)) # Convert list into string
TypeError: sequence item 0: expected string, int found
What is wrong?

You can use str() to transform each element:
print ''.join([str(x) for x in xline])

Related

How to convert a string array to float array?

I basically first converted a multidimensional array to a string array in order to set the values as my dictionary key, and now I need to convert the string array back to a regular float array. For example, what I have is:
str_array = ['[0.25 0.2916666666666667]', '[0.5833333333333334 0.2916666666666667]',
'[0.5555555555555555 0.3333333333333332]']
And I literally just need it back as a regular array
array = [[0.25 0.2916666666666667], [0.5833333333333334 0.2916666666666667],
[0.5555555555555555 0.3333333333333332]]
I have tried all the following : (*independently)
for i in str_arr:
i.strip("'")
np.array(i)
float(i)
Yet none of them work. They either cannot convert str --> float or they still keep the type as a str. Please help.
Use ast.literal_eval to convert str to another data type
import ast
str_array = ['[0.25 0.2916666666666667]', '[0.5833333333333334 0.2916666666666667]',
'[0.5555555555555555 0.3333333333333332]']
result = [ast.literal_eval(i.replace(" ", ",")) for i in str_array]
print(result) # [[0.25, 0.2916666666666667], [0.5833333333333334, 0.2916666666666667], [0.5555555555555555, 0.3333333333333332]]
You can also use the basic function eval.
[eval(x.replace(" ",",")) for x in str_array]

Converting str items in a dictionary to int and converting datetime.datetime variable to int

I know have this for loop that looks like this:
for i in my_dict[hostname]:
try:
if i == '':
except ValueError:
pass
i = int(i)
print(type(i))
It is giving me a syntax error and im unsure where or why.
Not sure I really understand your purpose, but converting a string of an int is straight-forward in Python :
>>> s = '123'
>>> int(s)
123
To convert a datetime to an int, you can convert it to a timestamp and then to an int:
timestamp = datetime.timestamp(d)
The timestamp is already a number that you can do operations on:
>>> d.timestamp()
1562855175.285529
>>> d.timestamp() - 1
1562855174.285529
Like #EuclidianHike said, you can easily convert str to int with int("str")
Make a 2nd list containing the values of 'scores' but in integer form by doing:
int_scores = []
for i in my_dict['scores']:
int_s = int(i)
int_scores.append(int_s) #Add indention as I cannot do it here on stackoverflow

byte literal array to string

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]

TypeError: 'str' object does not support item assignment (Python)

So this is what I'm trying to do:
input: ABCDEFG
Desired output:
***DEFG
A***EFG
AB***FG
ABC***G
ABCD***
and this is the code I wrote:
def loop(input):
output = input
for index in range(0, len(input)-3): #column length
output[index:index +2] = '***'
output[:index] = input[:index]
output[index+4:] = input[index+4:]
print output + '\n'
But I get the error: TypeError: 'str' object does not support item assignment
You cannot modify the contents of a string, you can only create a new string with the changes. So instead of the function above you'd want something like this
def loop(input):
for index in range(0, len(input)-3): #column length
output = input[:index] + '***' + input[index+4:]
print output
Strings are immutable. You can not change the characters in a string, but have to create a new string. If you want to use item assignment, you can transform it into a list, manipulate the list, then join it back to a string.
def loop(s):
for index in range(0, len(s) - 2):
output = list(s) # create list from string
output[index:index+3] = list('***') # replace sublist
print(''.join(output)) # join list to string and print
Or, just create a new string from slices of the old string combined with '***':
output = s[:index] + "***" + s[index+3:] # create new string directly
print(output) # print string
Also note that there seemed to be a few off-by-one errors in your code, and you should not use input as a variable name, as it shadows the builtin function of the same name.
In Python, strings are immutable - once they're created they can't be changed. That means that unlike a list you cannot assign to an index to change the string.
string = "Hello World"
string[0] # => "H" - getting is OK
string[0] = "J" # !!! ERROR !!! Can't assign to the string
In your case, I would make output a list: output = list(input) and then turn it back into a string when you're finished: return "".join(output)
In python you can't assign values to specific indexes in a string array, you instead will probably want to you concatenation. Something like:
for index in range(0, len(input)-3):
output = input[:index]
output += "***"
output += input[index+4:]
You're going to want to watch the bounds though. Right now at the end of the loop index+4 will be too large and cause an error.
strings are immutable so don't support assignment like a list, you could use str.join concatenating slices of your string together creating a new string each iteration:
def loop(inp):
return "\n".join([inp[:i]+"***"+inp[i+3:] for i in range(len(inp)-2)])
inp[:i] will get the first slice which for the first iteration will be an empty string then moving another character across your string each iteration, the inp[i+3:] will get a slice starting from the current index i plus three indexes over also moving across the string one char at a time, you then just need to concat both slices to your *** string.
In [3]: print(loop("ABCDEFG"))
***DEFG
A***EFG
AB***FG
ABC***G
ABCD***

'int' object and 'float' object not callable error

I have a post request returning a list: [u'2']
I am trying to extract the number and turn it into and integer but I keep getting either 'float' object not callable or 'int' object not callable.
Here is what I have tried so far:
speed = [u'2']
strSpeed = speed[3]
intSpeed = int(strSpeed)
and
strSpeed = speed[3]
intSpeed = float(strSpeed)
and
strSpeed = speed[3]
intSpeed = int(float(strSpeed))
It seems that I can do:
print float(strSpeed)
but I can't return it.
Any ideas?
You have a list of Unicode strings:
>>> speed
[u'2']
Obtain the first item from the list, it's a Unicode string:
>>> speed[0]
u'2'
Convert this string to an integer:
>>> int(speed[0])
2
Here you are.
Your speed variable has only a single item, so you can only access index [0]
>>> int(speed[0])
2
>>> speed[0]
'2'
The u is a prefix to declare a unicode string literal. So speed is just a list with a single unicode string.
Not sure exactly what you are trying to do but if you have a list of string items and you want to extract and convert to integters or floats, you could do the following:
stringlist = ["1", "2", "3.2"]
intlistitem = int(stringlist[0])
print(intlistitem)
floatlistitem = float(stringlist[2])
print(floatlistitem)

Categories