Wednesday, February 1, 2012

Funny Things Python Does 1

Multiplying String


You may have already tried this if you've been experimenting.  What happens when you multiply a string by an integer?  Let's try it:

print "python" * 3



Whoa!  What happened?  Were you expecting an error?

Python sometimes has special behavior for certain operations.  This is an example.  Python takes the string "python" and concatenates (from Latin meaning "linked together") it three times, giving you the result of a "pythonpythonpython" string.

But what good is it, you ask?  Say you wanted to have a line of "-" characters separating print lines on screen. Instead of typing (and counting) all those hyphens, you could write something like this:

print "-" * 80



Pretty cool, huh?  Be on the lookout for different ways of using shortcuts in your code.  They can save you lots of time and frustration.

3 comments:

  1. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    Python Training in electronic city, Bangalore | #pythontraininginelectroniccity #pythontraining

    DataSciencewithPythonTraininginelectroniccity,Bangalore | #datasciencewithpythontraininginelectroniccity #datasciencewithpythontraining

    ReplyDelete
  2. Linking is very useful thing.you have really helped lots of people who visit blog and provide them use full information.DataScience with Python Training in Bangalore


    ReplyDelete