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. This is one of the huge number of changes that was introduced in this Python 3 version, and sometimes you need to go back to the documentation to really work out how to use them. Below is a quick example on how you could use the new Sep.

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)

I will find time over the weekend to update this post and add a lot more examples here. I see lots of people searching for how to use sep - and it's important to have various examples that demonstrate how to effectively use it.

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.

No comments:

Related Posts with Thumbnails