Python Notes-4

In continuation from Python Notes-3
Python Notes-2
Python Notes-1

There are proper ways to format the string in python there is str.format() method then there is % operator like in c


print "My name is %s." % myName
print "I weigh %d k.g." % myWeight

I can do away just with simple print and print with end=”. When I don’t need new line just after a print. Rest I manage with string concatenation and str() function for converting to str.

the str() flota() int() function
“I am “ + str(29) + “ years old.”

There are couple of interview questions where you need to convert ascii to char and vice-versa. Python gives a very good way to do this using chr() and ord() functions.

>>> chr(0)
'\x00'
>>> ord('0')
48

Slicing with step


var[3:7:2] start : stop: step

reverse a string:


str[::-1]

We will come back to ord(), chr() and reversing a str again.


round(9.7)
10

Multiple assignment

var = ['fat', 'orange', 'loud']
>>> size, color, disposition = var

The number of variables and the length of the list must be exactly equal, or Python will give you a ValueError.

The multiple assignment trick can also be used to swap the values in two variables:

>>> a, b = 'Alice', 'Bob'
>>> a, b = b, a

To be continued …

Advertisements

One thought on “Python Notes-4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s