By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,345 Members | 1,783 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,345 IT Pros & Developers. It's quick & easy.

Newbie question: casting problem

P: 1
Hello I am starting to use Python.
I found a nice little example for subsituting and splitting texts and counting words separated by defined expressions (in the example , and blanks). Unfotunately there is an error in this example regarding the casting of strings: (see the code below):
import re
while 1:
Zeile = fh.readline()
if Zeile =='':break
mZeile = re.sub('[ ,\r\n]{1,}$','',Zeile)
Wert = re.split('[ ,]{1,}',mZeile)
for i in range(len(Wert)):
print'Wert:', Wert[i], '\n', len(Wert)
summe = summe + float(Wert[i])
print"Summe: ", summe, \
'\nEingabedaten: ', n, \
'\nMittelwert : ', summe/n, '\n'
except IOError, (errno, strerror):
print'Datei input.txt nicht lesbar. \n', \
'Fehlernummer:', errno, '\n', \
'Fehlermeldung: ', strerror

Using the example above I am getting the following error message:

--> invalid literal for float(): ... fisrt word in file input.txt

The content of my input.txt is:
hugo HiHo,002
alter ego 009
ha, what 006
END !? NO 010

Any idea how this casting problem could be solved?

Bye Guncrew
Mar 12 '08 #1
Share this Question
Share on Google+
1 Reply

P: 314
Expand|Select|Wrap|Line Numbers
  1.         summe = summe + float(Wert[i])
You cannot float cast any characters. .. are you trying to count the number of words? If so, just simply use:
Expand|Select|Wrap|Line Numbers
  1. summe += 1
Mar 12 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.