A Python newbie ask a simple question

Steve Holden steve at holdenweb.com
Sat Jul 14 02:42:41 CEST 2007


Jeff McNeil wrote:
> The raw_input built-in returns a string.  The '[0]' subscript returns
> the first character in the user supplied response as strings support
> indexing.
> 
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
>>>> mystr = "asdf"
>>>> mystr[0]
> 'a'
> 
>>>> raw_input("Another one, please: ")[0]
> Another one, please: ASDF
> 'A'
> 
> -Jeff
> 
> On 7/13/07, xing93111 at gmail.com <xing93111 at gmail.com> wrote:
>> what does the statement "choice = raw_input(prompt)[0]" mean? I don't
>> know why there is a '[0]' in the statement.
>>
Of course it's not a very good way to handle input from a "defensive 
programming" point of view, since it fails and raises an exception when 
the user hits return:

 >>> a = raw_input("Bzzzt:")[0]
Bzzzt:
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
IndexError: string index out of range
 >>>

The best way to learn Python is to spend time typing it in to an 
interactive interpreter session.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list