Python : Crash Course Part 3 – Strings

After completing basic arithmetic and variable assignment, its time to move on to strings in python.

You can use single or double quotes to declare a string as shown below :

In[1] : ' hello world '
Out[1]: ' hello world '
In[2] : "hello world"
Out[2]: "hello world"

Wrapping double quotes around single quote for sentences can be dealt with as shown below :

In[3] : " I can't quit "
Out[3]: " I can't quit"

Print Statement –

This is the official way of displaying a string in python, note how the Out indicator & the single quotes are gone while using the print statement :

In [4]: x = ' hello world'
In [5]: print(x)
        hello world

Print Formatting –

This method is used when you want to repeatedly use variables within your statements. format is a special method of the string that enables inserting of variables within the {} brackets as per the order specified within the format curly bracket.

      y='the analytics engine'
      z='The number {} blog in the field of data science is {}'.format(x,y)
      The number 1 blog in the field of data science is the analytics engine

String Indexing –

Python indexes every character in a string. The indexing starts at 0 in python. Let’s say we have a string

In [8]:s = 'engine'

If we had to break it down then python would have indexed the first character ‘a’ at index 0, second character ‘n’ at index 1 and so on..

In [9]:s[0]

We can use the slice syntax using the colon notation (:) which can be used to grab a substring or set /block of characters.

In [10]:s[:4]

Since the indexing starts at 0, the slicing happens till the 4th character which is actually at index position 3.

“So basically the number after the slice indicator is the (position of the character) or (the position of the character – 1 which would be the index location internally).

In python terms it would be 4th character :4 or s[3]”

In [11]:s[2:4]

The above code retrieved data from index s[2] which is ‘g’ and s[3] which is ‘i’. It will not pick s[4] which is ‘n’ as mentioned above, it would pick the 4th character or s[3]

This is little tricky, but with some practice it would be easy and I will explain more of such in the next blog when we will discuss about python lists.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s