1

My list is ['1','2','to','3']

I need to write a logic that

  • convert '1' '2' which is string to 1, 2 which is integer
  • print an error msg since 'to' string is included and cannot be converted to integer

Here's the code I have right now:

def average_file(filename):
 inputFile = open(filename, "r")
 inList = []
 results = []
 n = []
 for line in inputFile:
 inList.append(line.strip()) #inList.append(line)
 n = [int(elem) for elem in inList if elem.isdigit()] #I only remove the string and leave integer in my list, but I need a check logic to print error msg
 results = list(map(int, n))
 inputFile.close()
 results = sum(results)/len(results)
 return results
TrebledJ
9,0257 gold badges28 silver badges50 bronze badges
asked Dec 20, 2018 at 15:56
2
  • Not entirely sure what your question is right now and how it ties in with your code. Why are you computing results every time a line is read? (It's not exactly wrong, but it's fishy.) Commented Dec 20, 2018 at 16:00
  • 2
    What do you want to do if you get non numbe? Do you want to throw an error and continue or break? Commented Dec 20, 2018 at 16:02

5 Answers 5

2

Few things:

  • The pythonic way to do it is to expect it to be an all digit value and handle the error when it is not.
  • You can use with to handle your file lifetime.
  • You can calculate sum and count of elements during the reading without saving additional array (and therefore know the average).
  • strip is redundant when parsing to int like that int(variable):

There you go:

def average_file(filename):
 summary = 0
 count = 0
 with open(filename, "r") as inputFile:
 for line in inputFile:
 try:
 summary += int(line)
 count += 1
 except ValueError as e:
 print('Can not parse "{0}" to a number'.format(line))
 # If reached here one of the values in the file is not a number and None is returned immediately
 return None
 # If count is 0 return None, otherwise return the average
 return (summary / count) if count else None

The answer was edited after some clarifications from OP:
Immediately return None when one of the values is not a number.

answered Dec 20, 2018 at 16:11
5
  • I input a test file (.txt) with string. I expect the error msg. However, it returned the float 51.22222222222222. the below is the content of my testing file 1 2 3 4 5 wut 6 7 8 9 Commented Dec 20, 2018 at 16:23
  • @potentialwjy It makes no sense the average from my code came out 51.222 from input that the maximum value was 9. Something else is wrong there. For the array [1, 2, 3, 4, 5, 'wut', 6, 7, 8, 9] the result will be 5 and on the console you will see Can not parse "wut" to a number. Commented Dec 20, 2018 at 16:30
  • @potentialwjy Is each value on the file is in a new line? Commented Dec 20, 2018 at 16:34
  • my fault, I used the testing file in the class which is invisible..Now I use my testing file 1,2,3...wut...9, it shows: Can not parse "wut " to a number Out[192]: 5.0 the expectation is to have the error msg only. It should not have the 5.0 as average in this case. Any thought? Thanks for your help! Commented Dec 20, 2018 at 16:42
  • @potentialwjy I edited my answer (added a return None at the except handler), have a look Commented Dec 20, 2018 at 16:49
2

convert '1' '2' which is string to 1, 2 which is integer print an error msg since 'to' string is included and cannot be converted to integer

source = ['1', '2', 'to', '3']
result = []
for item in source:
 try:
 result.append(int(item))
 except ValueError as ex:
 print('Not integer: {}'.format(item))
print(result)
answered Dec 20, 2018 at 16:03
1
  • Agree, just have written ex mechanically Commented Dec 20, 2018 at 16:30
1

Attempt to convert each item to the list of results. If the conversion fails, print an error message.

l = ['1','2','to','3']
result = []
for item in l:
 try:
 result.append(int(item))
 except ValueError:
 print(item)
answered Dec 20, 2018 at 16:03
1

You can use a try/except block to separate the valid integer literals from everything else:

candidates = ['1','2','to','3']
for candidate in candidates:
 try: # attempt the conversion
 value = int(candidate)
 except ValueError: # conversion failed!
 print(candidate, 'is not an integer')
 else: # conversion succeeded
 print(candidate, 'is the integer', value)

In your case, you can just collect the values in the else clause:

results = []
with open(filename) as input_file:
 for line in inputFile:
 try:
 value = int(line.strip())
 except ValueError:
 print(line.strip(), 'is not an integer')
 else:
 results.append(value)
answered Dec 20, 2018 at 16:04
1
  • your solution almost works...but my testing result shows: wut is not an integer 5.0 my testing file is a txt with below info: 1 2 3 4 5 wut 6 7 8 9 Commented Dec 20, 2018 at 16:37
0
l = ['1', '2', 'word', '4']

You can do:

n = [int(i) if i.isdigit() else print('\nNot able to convert: '+i) for i in l]

Output:

Not able to convert: word
l = [1, 2, None, 4]
answered Dec 20, 2018 at 16:03
3
  • 2
    Wouldn't that add None elements to n... 🤔 Edit: I'm getting a syntax error for else print. Commented Dec 20, 2018 at 16:05
  • I don't think print statements are suitable for list comprehensions. Commented Dec 20, 2018 at 16:26
  • Yeah you are right. I should have tried it, I'll modify it Commented Dec 20, 2018 at 16:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.