How can I create an array of Unicode characters in Python? - python

I am using Repl.it.
import array as arr
my_array = arr.array("u", [u"3", u"6", u"9", u"12"])
print(my_array)
print(type(my_array))
print(type(my_array[0]))
The above source code produces the following error:
Traceback (most recent call last):
File "main.py", line 3, in <module>
my_array = arr.array("u", [u"3", u"6", u"9", u"12"])
TypeError: array item must be unicode character
Why the source code isn't working?

Array type "u" corresponds to a single Unicode character. The initializer contains a two-character item u"12". Perhaps you want something like:
arr.array("u", [u"3", u"6", u"9", u"1", u"2"])

Related

words into numbers scrape

When I scrape a webpage it returns this: 42,834.56
Apparently, it extracts it as a word (because when I try to sum it whit the other ones retrieve in excel it doesn't work). How can I convert it into a number?
I'm copying from the cmd:
Here is an error when I write it with int():
Traceback (most recent call last):
File "C:\Users\Windows\Desktop\py4e\callao.py", line 337, in <module>
print(int(peso))
ValueError: invalid literal for int() with base 10: '42,834.56\xa0'
Here is an error when I write it with float():
Traceback (most recent call last):
File "C:\Users\Windows\Desktop\py4e\callao.py", line 337, in <module>
print(float(peso))
ValueError: could not convert string to float: '42,834.56\xa0'
You might need to remove ',' from the number. Try this:
float("".join(peso.split(',')))
a = "42,834.56"
b = float(a.replace(",",""))
print(type(b))
# output: <class 'float'>
You can try this.
Strip off the \xa0 character.
Remove the , from the string
Convert it to float.
s = '42,834.56\xa0'
s = s.strip()
print(float(s.replace(',','')))
You can store the scraped value in a variable and convert to float in python. Here's the function:
def convert_to_float(peso):
return float(peso.replace(',',''))
And here's the call to the function:
peso = '42,834.56'
convert_to_float(peso)
Output:
42834.56
Now you can sum it with others.
Edit -
It seems you have scraped \xa0 also along with the string. So to handle that:
def convert_to_float(peso):
peso = peso.split("\\")[0]
return float(peso.replace(',',''))
peso = '42,834.56\xa0'
convert_to_float(peso)
Output will be same as above.

How can I select a char from a string inside a list in python and compare it with a single char?

Here is the code where I try to take the "t" char from the "two" string from the li list and compare it to a single "t" char:
li=["one","two","three"];
choice=1;
if li[choice[1]]=="t":
print("valid");
else:
print("unvalid");
The problem is that when I run it, it says:
Traceback (most recent call last):
File "C:\Users\Yobob\Documents\cours\ISN\ProjetISN\testPython.py", line 3, in <module>
if li[choice[1]]=="t":
TypeError: 'int' object is not subscriptable
choice[1] is doing 1[1] which doesn't make sense. I think you want li[choice][1]. i.e.
if li[choice][1] == "t":

python regular expression error

I am trying do a pattern search and if match then set a bitarray on the counter value.
runOutput = device[router].execute (cmd)
runOutput = output.split('\n')
print(runOutput)
for this_line,counter in enumerate(runOutput):
print(counter)
if re.search(r'dev_router', this_line) :
#want to use the counter to set something
Getting the following error:
if re.search(r'dev_router', this_line) :
2016-07-15T16:27:13: %ERROR: File
"/auto/pysw/cel55/python/3.4.1/lib/python3.4/re.py", line 166,
in search 2016-07-15T16:27:13: %-ERROR: return _compile(pattern,
flags).search(string)
2016-07-15T16:27:13: %-ERROR: TypeError: expected string or buffer
You mixed up the arguments for enumerate() - first goes the index, then the item itself. Replace:
for this_line,counter in enumerate(runOutput):
with:
for counter, this_line in enumerate(runOutput):
You are getting a TypeError in this case because this_line is an integer and re.search() expects a string as a second argument. To demonstrate:
>>> import re
>>>
>>> this_line = 0
>>> re.search(r'dev_router', this_line)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/user/.virtualenvs/so/lib/python2.7/re.py", line 146, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
By the way, modern IDEs like PyCharm can detect this kind of problems statically:
(Python 3.5 is used for this screenshot)

How to copy input file ch by ch and use format in python?

I have been trying to copy the input file character by character and then trying to format them to avoid any kind of alignment issue. The first item in the input file is 50 characters long, the second item is 6 characters long, third is 3 characters long, fourth is 25 characters long, and the fifth is 4 characters long. I am not allowed to use list or tuple. The following is my code:
input_file=open('measles.txt','r')
f1=input('file name: ')
output_file=open(f1,'w')
for line in input_file:
newstring=''
line=line.strip()
for ch in line:
#I am trying to format the first two items in the input file
print('{0:50}{51:57}'.format(line[0:50],line[51:57]),file=output_file)
input_file.close()
output_file.close()
and the error I am getting is the following:
Traceback (most recent call last):
File "C:/Users/Dasinator/Documents/Books IX/Python Examples/proj07.py", line 10, in <module>
print('{0:50}{1:57}'.format(line[0:50],line[51:57]),file=output_file)
IndexError: tuple index out of range
Could anyone point out the error in the code and recommend ways to fix it? Thanks
Andorra WB_HI
Andorra WB_HI
Angola WB_LMI
Angola WB_LMI
Angola WB_LMI
The output still is not looking perfectly aligned.
This is how I modified my code and still having some trouble.
print('{0:50s}{1:6s}{2:<3s}{3:<25s}{4:<4s}'.format(line[0:50],line[50:56]),line[56:59],line[59:84],line[84:87],file=output_file)
and the output that I am getting is
Traceback (most recent call last):
File "C:/Users/Dasinator/Documents/Books IX/Python Examples/proj07.py", line 10, in <module>
print('{0:50s}{1:6s}{2:<3s}{3:<25s}{4:<4s}'.format(line[0:50],line[50:56]),line[56:59],line[59:84],line[84:87],file=output_file)
IndexError: tuple index out of range
Looks like you've misunderstood how .format works, and what the formatting string should look like.
When you write a string "{0:50}{1:50}".format(stuff0, stuff1) the colon separates the index (before), from the number of characters that the string should take up when printed.
So, when you do:
print('{0:50}{51:57}'.format(line[0:50],line[51:57]),file=output_file)
you're telling python to use the 51st argument to .format. What you actually mean is the second argument to .format, or the 51st character in the string.
Presumably, what you actually want to do here is print the 0th-50th characters of the line, and the 51st-57th characters. That will look like:
print('{0:10}{1:10}'.format(line[0:50],line[51:57]),file=output_file)
Additionally, I don't know what you mean the file argument to do, but it's probably not going to do what you expect.
Why 51 here in second param: {0:50}{51:57}?, should be 1:
print('{0:50}{1:57}'.format(line[0:50],line[51:57]),file=output_file)
# ^^^
As test:
>>> print('{0:10}{57:10}'.format(10,20))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> print('{0:10}{1:10}'.format(10,20))
10 20
To align second column to left side, use < char before width:
print('{0:50}{1:<57}'.format(line[0:50],line[51:57]),file=output_file)

python convert string "0" to float gives error

i have the following code in my python script, to launch an application and grab the output of it.
An example of this output would be 'confirmed : 0'
Now i only want to know the number, in this case zero, but normally this number is float, like 0.005464
When i run this code it tells me it cannot convert "0" to float. What am i doing wrong?
This is the error i get now:
ValueError: could not convert string to float: "0"
cmd = subprocess.Popen('/Applications/Electrum.app/Contents/MacOS/Electrum getbalance', shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
if "confirmed" in line:
a,b=line.split(': ',1)
if float(b)>0:
print "Positive amount"
else:
print "Empty"
According to the exception you got, the value contained in b is not 0, but "0" (including the quotes), and therefore cannot be converted to a float directly. You'll need to remove the quotes first, e.g. with float(b.strip('"')).
As can be seen in the following examples, the exception description does not add the quotes, so they must have been part of the original string:
>>> float('"0"')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: "0"
>>> float('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: a
I have tested the code and found that split(': ', 1) result contains string
>>> line = "1: 456: confirmed"
>>> "confirmed" in line
True
>>> a,b=line.split(': ', 1)
>>> a
'1'
>>> b
'456: confirmed'

Categories