So i'm trying to work with floats as elements in Python lists but I keep getting this error. I tried making each value a string and then converting it to a float when calling the array to print but that doesn't seem to work either
P1 = [45.100000, ‐65.400000]
print(P1[0])
SyntaxError: invalid character in identifier
Attempt #2
P1 = ["45.100000", "‐65.400000"]
print(float(P1[1]))
ValueError: could not convert string to float: '‐65.400000'
I have a feeling the issues have to do with the negative value in front of the 2nd elements (# index 1)
There is a problem with the hyphen you are using. If you cut and paste the hyphen in your list p1, and check the unicode, it gives:
>>> ord('‐')
8208
Whereas the proper negative or subtraction sign should be:
>>> ord('-')
45
Depending on how you got that list, you either have to figure out why that character got included, or re-type it with the proper Hyphen-Minus
I copied your code and ran it, and all I had to do was replace the "-" Seems like you were using a bad character. Try this;
P1 = [45.100000, -65.400000]
This is because your - is not a minus sign but a hyphen character:
>>> "‐65.400000".encode('utf-8') # copy from your example
b'\xe2\x80\x9065.400000'
>>> "-65.400000".encode('utf-8') # Replace with my minus
b'-65.400000'
\xe2\x80\x90 is a hyphen character, see here: your hyphen is U+2010 and the hyphen-minus is U+002D
Related
I got an strange error I have never seen before and I tried to find some information over the web but without sucess.
I try to do a simple thing, converting an str to flaot. When I print the value it is in classic number style (37 442.20) but when I want to convert it to flaot I get an Error showing the value in a mix of number and letter (37\u202f442.20). With the following lines I get :
print(value)
print(type(value))
37 442.20
<class 'str'>
print(float(value))
ValueError: could not convert string to float: '37\u202f442.20'
Someone know what's going wrong here ?
s = "37 442.20"
print (float(s.replace(' ','').encode('ascii', 'ignore')))
Output:
37442.2
You have both the space and encoding problems.
So you use replace() method on your string and encode() to pass through each and print your float.
In order to avoid error upon conversion of a list of mixed non digit string and digit strings, and considering your encoding problem, you can do:
import re
sl = ["37 442.20","aaa.83","4a3.","aaaa","345"]
for s in sl:
s = s.replace(' ','').encode('ascii', 'ignore')
if re.match(b"^([0-9]+){0,1}[.]{0,1}([0-9]+)$",s):
print (float(s))
else:
print ("%s not digit" % s.decode())
Output:
37442.2
aaa.83 not digit
4a3. not digit
aaaa not digit
345.0
It’s simply because you have white space between digits. Remove the white space and pass the value to float and it should work fine.
One way to do this:
value = “”.join(‘37 442.20’.split())
print(float(value))
The \u202f character is not a normal space.
https://www.fileformat.info/info/unicode/char/202f/index.htm
You can try remove them first before converting. For example:
u'37\u202f442.20'.encode('ascii', 'ignore')
I have a problem with a command of python. I want my program to read a specific line from my file, and here I haven't problem. The problem is when I have to convert the line in a float (I need of float to calculate some equation). My program is:
f=open('coeff.txt')
lines=f.readlines()
k1=lines[0]
k1 = float(k1)
k2=lines[1]
k2 = float(k2)
k3=lines[2]
k3 = float(k3)
k4=lines[3]
k4 = float(k4)
And the file coeff.txt is:
1.2*1e-1
6.00*1e-34
1.13*1e-4
6.9*1e-16
that is 1.2*10^(-1) , 6*10^(-34), 1.13*10^(-4), 6.9*10^(-16)
and I get the error:
ValueError: could not convert string to float: '6.00*1e-34\n'
(obviously that this error is referred to each line.
Can you help me, please?
Python doesn't know how to interpret '6.00*1e-34\n' as a float. You will have to clean your data before you can actually use it.
Eventually, you will want to have each line in a format like this:
6.00e-34
Looking at it closely, it seems like the only differences are the \n at the end of the line, and the 1* in the middle.
You can get rid of the newline character at the end of the string (\n) by calling the .strip() method, and replace *1 with an empty string to get to the above format.
val = '6.00*1e-34\n'
cleaned_val = val.strip().replace('*1', '')
print(float(cleaned_val))
>>> 6e-34
Edit: It seems like the presence of the newline character doesn't really matter - so you only need to replace the *1 part of your string. I'm leaving it in anyway.
Your problem is the operator *
a = "\Virtual Disks\DG2_ASM04\ACTIVE"
From the above string I would like to get the part "DG2_ASM04" alone. I cannot split or strip as it has the special characters "\", "\D" and "\A" in it.
Have tried the below and can't get the desired output.
a.lstrip("\Virtual Disks\\").rstrip("\ACTIVE")
the output I have got is: 'G2_ASM04' instead of "DG2_ASM04"
Simply use slicing and escape backslash(\)
>>> a.split("\\")[-2]
'DG2_ASM04'
In your case D is also removing because it is occurring more than one time in given string (thus striping D as well). If you tweak your string then you will realize what is happening
>>> a = "\Virtual Disks\XG2_ASM04\ACTIVE"
>>> a.lstrip('\\Virtual Disks\\').rstrip("\\ACTIVE")
'XG2_ASM04'
I have this string and I need to get a specific number out of it.
E.G. encrypted = "10134585588147, 3847183463814, 18517461398"
How would I pull out only the second integer out of the string?
You are looking for the "split" method. Turn a string into a list by specifying a smaller part of the string on which to split.
>>> encrypted = '10134585588147, 3847183463814, 18517461398'
>>> encrypted_list = encrypted.split(', ')
>>> encrypted_list
['10134585588147', '3847183463814', '18517461398']
>>> encrypted_list[1]
'3847183463814'
>>> encrypted_list[-1]
'18517461398'
Then you can just access the indices as normal. Note that lists can be indexed forwards or backwards. By providing a negative index, we count from the right rather than the left, selecting the last index (without any idea how big the list is). Note this will produce IndexError if the list is empty, though. If you use Jon's method (below), there will always be at least one index in the list unless the string you start with is itself empty.
Edited to add:
What Jon is pointing out in the comment is that if you are not sure if the string will be well-formatted (e.g., always separated by exactly one comma followed by exactly one space), then you can replace all the commas with spaces (encrypt.replace(',', ' ')), then call split without arguments, which will split on any number of whitespace characters. As usual, you can chain these together:
encrypted.replace(',', ' ').split()
This question already has answers here:
Remove a prefix from a string [duplicate]
(6 answers)
Closed 6 months ago.
Trying to strip the "0b1" from the left end of a binary number.
The following code results in stripping all of binary object. (not good)
>>> bbn = '0b1000101110100010111010001' #converted bin(2**24+**2^24/11)
>>> aan=bbn.lstrip("0b1") #Try stripping all left-end junk at once.
>>> print aan #oops all gone.
''
So I did the .lstrip() in two steps:
>>> bbn = '0b1000101110100010111010001' # Same fraction expqansion
>>> aan=bbn.lstrip("0b")# Had done this before.
>>> print aan #Extra "1" still there.
'1000101110100010111010001'
>>> aan=aan.lstrip("1")# If at first you don't succeed...
>>> print aan #YES!
'000101110100010111010001'
What's the deal?
Thanks again for solving this in one simple step. (see my previous question)
The strip family treat the arg as a set of characters to be removed. The default set is "all whitespace characters".
You want:
if strg.startswith("0b1"):
strg = strg[3:]
No. Stripping removes all characters in the sequence passed, not just the literal sequence. Slice the string if you want to remove a fixed length.
In Python 3.9 you can use bbn.removeprefix('0b1').
(Actually this question has been mentioned as part of the rationale in PEP 616.)
This is the way lstrip works. It removes any of the characters in the parameter, not necessarily the string as a whole. In the first example, since the input consisted of only those characters, nothing was left.
Lstrip is removing any of the characters in the string. So, as well as the initial 0b1, it is removing all zeros and all ones. Hence it is all gone!
#Harryooo: lstrip only takes the characters off the left hand end. So, because there's only one 1 before the first 0, it removes that. If the number started 0b11100101..., calling a.strip('0b').strip('1') would remove the first three ones, so you'd be left with 00101.
>>> i = 0b1000101110100010111010001
>>> print(bin(i))
'0b1000101110100010111010001'
>>> print(format(i, '#b'))
'0b1000101110100010111010001'
>>> print(format(i, 'b'))
'1000101110100010111010001'
See Example in python tutor:
From the standard doucmentation (See standard documentation for function bin()):
bin(x)
Convert an integer number to a binary string prefixed with “0b”. The result is a valid Python expression. If x is not a Python int object, it has to define an index() method that returns an integer. Some examples:
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
If prefix “0b” is desired or not, you can use either of the following ways.
>>> format(14, '#b'), format(14, 'b')
('0b1110', '1110')
>>> f'{14:#b}', f'{14:b}'
('0b1110', '1110')
See also format() for more information.