.

Sunday, July 10, 2011

Using Sep in Python

If you have been working with the latest Python 3 to a degree, chances are that you will have come across some very tricky and trivial piece of code that would run easily on Python 2.* but not on Python 3. There is a huge number of changes that was introduced in this version, and sometimes you need to go back to the documentation to really work out how to use them.

Here's simple example of that in action:

place = "London"
print("Hello from ", place, '!');

If you run that, you will get
Hello from London !

The new print() method by default inserts a space at the end of its arguments. To avoid that space you will need to explicitly specify the 'sep' keyword.

print ("Hello from ", place, "!", sep="") # Note the explicit " " after "Hello"
Another goodie is that you can easily get useful information about modules, classes, keywords, and functions, e. g.

>>> help(print)

However, if you have a much bigger text than the one shown above, you will need to concatenate them before printing. Here's an example of how you might also want to use it:
output = "".join(["Hello ",name,"!"])  # thats an empty string to start 

print(output)
As I have always said, use the >>> prompt to experiment to find which works best for you. It is one of the most powerful methods to learn how to use Python's huge collection of modules.

0 comments:

Related Posts with Thumbnails