convert a string from a list to a float - python

I have a list with strings. Some of the strings contain alphabets and some contain numbers. I want to convert one of the strings with numbers in it to a float but getting an error
the list is called x. the 3rd element of the list is numbers. I tried x[2] = float (x[2]) but it gives me :Value error: could not convert string to a float:%"
See line 12 of the code where I am comparing float(x[2]) with 100
def file_read(fname):
i = 0
content_array = []
with open(fname, 'r') as f:
#Content_list is the list that contains the read lines.
for line in f:
content_array.append(line)
x = content_array[i].split('|')
i = i + 1
x[2] = x[2].strip() # to delete any empty spaces
if float(x[2]) > 50.00:
print ('got one')
print x[2]
print i
file_read('flow.txt')

Around your if statement you can wrap a try/except block, the program will try to convert float(x[2]) to a float, but if it cannot (since its a string) it will execute the except portion of the code.
try:
if float(x[2]) > 50.0:
print('got one')
except:
# do something else, if x[2] is not a float
pass # if you don't want to do anything.

You can use regular expressions to check if it's a number, and then you can safely cast it to float.
import re
rgx = "^\d*\.?\d*$"
if re.match(rgx, x):
print("it's a number!")
x = float(x)

Related

Unable to extract numbers and sum them using regex and re.findall()

I try to extract numbers from a text file with regex. Afterward, I create the sum.
Here is the code:
import re
def main():
sum = 0
numbers = []
name = input("Enter file:")
if len(name) < 1 : name = "sample.txt"
handle = open(name)
for line in handle:
storage = line.split(" ")
for number in storage:
check = re.findall('([0-9]+)',number)
if check:
numbers.append(check)
print(numbers)
print(len(numbers))
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
if __name__ == "__main__":
main()
The problem is, if this string "http://www.py4e.com/code3/"
I gets add as [4,3] into the list and later summed up as 43.
Any idea how I can fix that?
I think you just change numbers.append(check) into numbers.extend(check)because you want to add elements to an array. You have to use extend() function.
More, you do not need to use ( ) in your regex.
I also tried to check code on python.
import re
sum = 0;
strings = [
'http://www.py4e.com/code3/',
'http://www.py1e.com/code2/'
];
numbers = [];
for string in strings:
check = re.findall('[0-9]+', string);
if check:
numbers.extend(check)
for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(sum)
I am assuming instead of 43 you want to get 7
The number variable is an array of characters. So when you use join it becomes a string.
So instead of doing this you can either use a loop in to iterate through this array and covert elements of this array into int and then add to the sum.
Or
you can do this
import np
number np.array(number).astype('int').tolist()
This makes array of character into array on integers if conversion if possible for all the elements is possible.
When I add the string http://www.py4e.com/code3/" instead of calling a file which is not handled correctly in your code above fyi. The logic regex is running through two FOR loops and placing each value and it's own list[[4],[3]]. The output works when it is stepped through I think you issue is with methods of importing a file in the first statement. I replaced the file with the a string you asked about"http://www.py4e.com/code3/" you can find a running code here.
pyregx linkhttps://repl.it/join/cxercdju-shaunpritchard
I ran this method below calling a string with the number list and it worked fine?
#### Final conditional loop
``` for number in numbers:
x = ''.join(number)
num = int(x)
sum = sum + num
print(str(sum)) ```
You could also try using range or map:
for i in range(0, len(numbers)):
sum = sum + numbers
print(str(sum))

Read only the numbers from a txt file python

I have a text file that contains these some words and a number written with a point in it. For example
hello!
54.123
Now I only want the number 54.123 to be extracted an converted so that the outcome is 54123
The code I tried is
import re
exp = re.compile(r'^[\+]?[0-9]')
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
if re.match(exp, line.strip()):
my_list.append(int(line.strip()))
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)
But this returns the error: ValueError: invalid literal for int() with base 10: '54.123'
Does anyone know a solution for this?
You can try to convert the current line to a float. In case the line does not contain a legit float number it returns a ValueError exception that you can catch and just pass. If no exception is thrown just split the line at the dot, join the 2 parts, convert to int and add to the array.
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
try:
tmp = float(line)
num = int(''.join(line.split(".")))
my_list.append(num)
except ValueError:
pass
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)
You can check if a given line is a string representing a number using the isdigit() function.
From what I can tell you need to just check if there is a number as isdigit() works on integers only (floats contain "." which isn't a number and it returns False).
For example:
def numCheck(string):
# Checks if the input string contains numbers
return any(i.isdigit() for i in string)
string = '54.123'
print(numCheck(string)) # True
string = 'hello'
print(numCheck(string)) # False
Note: if your data contains things like 123ab56 then this won't be good for you.
To convert 54.123 to 54123 you could use the replace(old, new) function.
For example:
string = 54.123
new_string = string.replace('.', '') # replace . with nothing
print(new_string) # 54123
This may help I am now getting numbers from the file I guess you were trying to use split in place of strip
import re
exp = re.compile(r'[0-9]')
my_list = []
with open('file.txt') as f:
lines = f.readlines()
for line in lines:
for numbers in line.split():
if re.match(exp, numbers):
my_list.append(numbers)
#convert to a string
listToStr = ' '.join([str(elem) for elem in my_list])
print(listToStr)

How to convert an integer into string without using in-built function?

I wanna ask how to convert an integer into string without using in-built function.
This is the original question:
Write a function string(ls) that returns a string representation of the list ls.
Note: do not use the built-in str() method for this task. We are attempting to emulate its behavior.
s = string(['a','b','c']) # '['a','b','c']'
s = string([1,2,3]) # '[1, 2, 3]'
s = string([True]) # '[True]'
s = string([]) # '[]'
Restrictions: Don't just return str(ls)! Don't use the str.join method, don't use slicing.
Here is my code:
def string(ls):
if len(ls)==0:
mess="'[]'"
return mess
elif isinstance(ls[0],str):
i=0
mess="'["
while True:
if i==len(ls)-1:
elem="'"+ls[i]+"'"
mess=mess+elem
break
else:
elem="'"+ls[i]+"', "
mess=mess+elem
i=i+1
mess=mess+"]'"
return mess
else:
i=0
mess="'["
while True:
if i==len(ls)-1:
elem=str(ls[i])+"]'"
mess=mess+elem
break
else:
elem=str(ls[i])+', '
mess=mess+elem
i=i+1
return mess
You can keep dividing a given integer by 10 and prepending the remainder to the output string. Use the ordinal number of '0' plus the remainder to obtain the ordinal number of the remainder, and then convert it to string using the chr function:
def int_to_string(i):
string = ''
while True:
i, remainder = divmod(i, 10)
string = chr(ord('0') + remainder) + string
if i == 0:
break
return string
so that:
print(int_to_string(0))
print(int_to_string(5))
print(int_to_string(65))
print(int_to_string(923))
would output:
0
5
65
923
This should work? I am fairly new so i do not know why your codes are so complicated.This should work too.
def int_to_string(i):
string = chr(ord("0") + i)
return string

Adding numbers in a string

I have a string as an input for the code I'm writing and let an example of the string be:
"12 inches makes 1 foot"
My goal is to have my code run through this string and just pull out the integers and add them. So the output for the string above would be 13. I am using try and except in here as well since another sample input string could be something like "pi is 3.14".
msg= "12 inches makes 1 foot"
thesum = 0
s= msg.split()
for a in s:
try:
if a == int(a):
a= int(a)
thesum += a
print (thesum)
except ValueError as e:
print("Value Error: no int present")
I did what is above and I am not getting it to add the value of a (if it is an int) to "thesum". How can I get this to work? Also, I do want to have it in the try, except format so that I can call the ValueError
There is no need to check equality with a string. In fact, just try '4' == 4 in an interpreter. The answer is False because strings and integers are never equivalent. Just put thesum += int(a) into the loop instead of your if statement. If you don't want try-except, use if a.isdigit(): instead of try: and take out except: altogether:
for a in s:
if a.isdigit():
thesum += int(a)
print(thesum)
A good way would be the combination of several built-ins:
string = "12 inches makes 1 foot"
total = sum(map(int, filter(str.isdigit, string.split())))
filter() finds only the characters that are digits. We then convert each to an integer with map() and find the total with sum().
a is str, and int(a) is int(if possible), so a == int(a) will never equal.
just add the value of int(a), if the convert fails, it will raise ValueError.
The following codes should work.
msg= "12 inches makes 1 foot"
thesum = 0
s= msg.split()
for a in s:
try:
thesum += int(a)
except ValueError as e:
print a
print thesum
I like "re" and comprehension to make it easier to read:
import re
print(sum(int(a) for a in re.findall(r'\d+', '12 inches make 1 foot')))
Then you can extend the regular expression for floats, etc.
Most of the earlier approaches discount the second input which is "pi is 3.14". Although question has been asked with stated assertion of parsing integer. It requires treatment of numbers as float to successfully process second input.
import unittest
import re
def isDigit(s):
return re.match(r'[\d.]+', s)
def stringParse(input):
input = [i.strip() for i in input.split()]
input = filter(lambda x: isDigit(x), input)
input = map(lambda x: float(x), input)
return sum(input)
class TestIntegerMethods(unittest.TestCase):
def test_inches(self):
self.assertEqual(stringParse("12 inches makes 1 foot"), 13.0)
def test_pi(self):
self.assertTrue(stringParse('pi is 3.14'), 3.14)
if __name__ == '__main__':
unittest.main()
Another take on the problem

Python if statement using CSV Data

I am reading in some data from a CSV file and then printing a value based on an if statement, but it doesn't seem to make sense to me. I would expect it would print equal to 1
PYTHON CODE:
import csv
#open CSV file
csvfile = open("C:\\python.csv", "rb")
data = csv.reader(csvfile)
data = [row for row in data]
#start loop through each item
for currentrow in range(1, 2): # numbers off due to array starting at 0
#grab one record data [row][col]
Count = data[currentrow][7]
print "Count equals: " + Count
if Count > 1:
print "greater than 1"
if Count == 1:
print 'equal to 1'
OUTPUT:
Count equals: 1.00
greater than 1
Your trouble stems from the fact that what you read from a file is always a string (i.e. str type). This means that even if the file contains a number, it is read into your variable as a string. Therefore, if your file looks like this:
myFile.txt:
2
And if you did:
with open('myFile.txt') as infile:
x = infile.readline()
then, x would have the value '2', which is a str type. This means, that if you did x*2, you'd get '22', because that's how strings multiply out.
What you really want, is to convert that sting into an int. This is called "casting a string into an integer" and can be done very simply:
y = int(x)
There's another type that you should be aware of: float. It is used to hold decimal numbers. So, if you were to say
x = 3.4
then x would be a float. You can also cast ints to floats:
z = float(y)
would turn z into a float, with the value 2.0
Now, onto your actual problem:
data = [row for row in data] # data is now a list of lists; each sublist is a list of strings
for currentrow in range(1,2):
Count = data[currentrow][7] # Count is now the string at index 7, of the sublist at index `currentrow`, i.e. 1.00
Count = float(Count) # Count is now the floating point value of the string '1.00'
Count = int(Count) # Count is now the integer value of 1.00, i.e. 1
if Count > 1:
print "greater than 1"
if Count == 1:
print "equal to 1"
Now, onto your second problem:
print 'Count equals ' + Count
Here, you are trying to add a str and an int. Well, those are incompatible types for addition. Therefore, you should cast the int into a str; and just like how strs can be cast into ints, ints can be cast into strs with a call to str():
Count_str = str(Count)
So when you want to print the value, you could do:
print "Count equals " + str(Count)
Of course, the print statement is a little more friendly and lets you do something like this:
print "Count equals", Count # no casting needed here

Categories

Resources