Results 1 to 4 of 4

Thread: Python: Is it possible to site a string with in a string?

  1. #1
    Join Date
    Apr 2009
    Location
    Minneapolis/St. Paul
    Beans
    90
    Distro
    Ubuntu 10.04 Lucid Lynx

    Python: Is it possible to site a string with in a string?

    I want to be able to have a string with in a string.
    Code:
    Example:
    
    food = ['Mexican','Italian']
    Mexican = ['Tacos','Burritos']
    
    print "My favorite food is:", food[0]
    
    OUTPUT:
    
    My favorite food is: ['Tacos','Burritos']
    Is it possible to do this??

  2. #2
    Join Date
    Jul 2007
    Location
    Austin, TX
    Beans
    Hidden!
    Distro
    Ubuntu 10.04 Lucid Lynx

    Re: Python: Is it possible to site a string with in a string?


  3. #3
    Join Date
    Jun 2009
    Location
    Land of Paranoia and Guns
    Beans
    194
    Distro
    Ubuntu 12.10 Quantal Quetzal

    Re: Python: Is it possible to site a string with in a string?

    This is possible, and is called nesting. Instead of a string, you can use a variable name to include it in a list. To use your example:
    PHP Code:
    Mexican = ['Tacos','Burritos']
    food = [Mexican,'Italian']

    print 
    "My favorite food is:"food[0
    OUTPUT:

    My favorite food is: ['Tacos', 'Burritos']

    Note the lack of quotes around Mexican in the food variable.
    Don't use W3Schools as a resource! (Inconsequential foul language at the jump)
    Open Linux Forums (More foul language, but well worth it for the quality of support and good humor.)
    If you want to discuss W3Schools, please PM me instead of posting.

  4. #4
    Join Date
    Apr 2007
    Location
    (X,Y,Z) = (0,0,0)
    Beans
    3,715

    Re: Python: Is it possible to site a string with in a string?

    I'd go for a dictionary here. It's much clearer and explicit and allows to do some nice things. Look at this:

    Code:
    #!/usr/bin/env python
    
    def main():
        food = {"mexican" : ["Tacos", "Burritos"],
                "italian" : ["Pizza", "Spaghetti", "Stromboli"]}
    
        choice = raw_input("What's your favorite food? ")
    
        # choice.lower() returns your input in lowercase... that makes this program
        # case non-sensitive.
        print("Your favorite food is: %s" % food[choice.lower()])
    
    if __name__ == "__main__": # Prevents execution when importing this module
        main()
    A dict is like an array, but instead of accesing the items by index, you do it by key. So, using strings as keys allows you to ask for input and use the very same input as the key for the data you want.

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •