0

I am trying to create a list where I need to input numbers as strings in one list and I am trying to do it with a while loop.

while input_list[-1] != "":
    input_list.append(raw_input())

However when numbers are entered they are returned as u'X', X being the number entered. I cannot perfrom mathematical calculations on these numbers.

I would usually use str() or int() but I cant generalise in this case.

Is there a cleaner way to remove the u' ' prefix than simpley using if statements?

deadfire19
  • 329
  • 2
  • 16

1 Answers1

2

The "u'' prefix" is trying to indicate the type of the value. You have strings here, not numbers. If you want to do math, you need to convert your strings to numbers. If they happen to enter a string that can't be converted to a number, you should tell the user what happened

user_typed = raw_input()
try:
    user_number = float(user_typed)
except ValueError:
    print "Couldn't convert this to a number, please try again: %r" % user_typed

See also: LBYL and EAFP

bukzor
  • 37,539
  • 11
  • 77
  • 111
  • if user_typed.isdigit == True: int(user_typed) #would be faster, I was counting on a fast solution, doesn't look like it exists. – deadfire19 Nov 05 '13 at 18:50
  • @deadfire19: It's not faster in the common case of the user typing a number, since you've scanned the string twice where I've done just once. I've updated my answer. – bukzor Nov 05 '13 at 19:00
  • I was curious, so I did some profiling on this topic. I found the try/except pattern is only faster if 98% of the input is numbers. http://paste.pound-python.org/show/qFTG4yTJdVSA3TVnQWkr/ – bukzor Nov 05 '13 at 19:56
  • We're talking about a situation where a user is typing in numbers. Profiling the difference between the two is irrelevant. – RemcoGerlich Nov 05 '13 at 20:42
  • @RemcoGerlich: From the OP "There are also strings in the list that I want to input." Please troll less. – bukzor Nov 06 '13 at 03:03
  • Yes, but in a situation where a user is typing in floats and strings (taking many seconds), I don't think a choice between isdigit() or try/except should be based on profiling something that takes milleseconds either way. Nobody will ever notice the speed difference. – RemcoGerlich Nov 06 '13 at 10:37