[Tutor] String and integer

wesley chun wescpy at gmail.com
Tue Oct 21 01:33:31 CEST 2008


>> def nr():
>>    nr1 = input('Enter value: ')
>>    print str(nr1).strip('nr0')
>>
>> The user input is always on the form "nr08756" and i'd like to take out
>> the "nr0" and then print the result.
>> I can see that there is a problem with a variable looking like "pn0123"
>> because i get: NameError: global name 'nr0123' is not defined.
>>
>> What is the right way to do this?
>
> raw_input() rather than input(). input evaluate whatever is entered;
> raw_input returns as a string whatever is entered.
>
> In Python 3 raw_input will be renamed input and the old input will go away.


everything that bob said... and more.  :-)

definitely never ever use input()... it is absolutely unnecessary and
a potential security hazard, hence the reason why its functionality
will be completely removed in 3.0. for now, as bob has suggested, use
raw_input() in the remaining 2.x releases then switch to input() for
3.x.

with regards to the rest of your query, if you are certain that the
first few chars of the input is 'nr0', you can just so nr1[3:] to get
the rest. if you want to play it safe, throw in a "if
nr1.startswith('nr0')" beforehand.

finally, be careful with strip(). you are not stripping just the "nr0"
with strip('nr0')... you are removing all 'n's, 'r's, and '0's from
your string, i.e.

>>> 'nr07890'.strip('nr0')
'789'

this is the reason why i suggested nr1[3:] instead... it chops off the
1st 3 chars and takes the remainer.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list