Programming in Python : Strings

Strings are also manupulated by python. Strings are represented within single quotes or double quotes. We can assign a string to a variable, and printed by using ‘print’. Strings can be surrounded by triple quotes “””. If there is \n the end of line, is echoed in the output.

>>> “Hello”+”world”

>>> a=’how are you?’

>>> print a
how are you?

The slice notation :

The slice notation is used to return the elements of a list or characters of a string as specified by the indices.

>>> string1 = ‘hello world’

>>> string1
‘hello world’

>>> string1[0:1]

>>> string1[0:4]

>>> string1[2:4]

>>> string1[:4]

>>> string1[3:]
‘lo world’

>>> string1[:0] = ‘Hai’
Traceback (most recent call last):
File “”, line 1, in
TypeError: ‘str’ object does not support item assignment

>>> string1[:0] + ‘Hai’

>>> string1
‘hello world’

>>> string1[:] + ‘Hai’
‘hello worldHai’

>>> ‘Hai’ + string1[:]
‘Haihello world’

The negative indices are using to indicate from the right to the begining of the string.

>>> string1[-1]

>>> string1[-4:-1]

>>> string1[-4:-2]

>>> string1[-4:0]

>>> string1[-1:-4]

>>> string1[-11:-1]
‘hello worl’

Author: Abhilash

Hey! My name is Abhilash - A Ruby developer for years, specialised on web programming, working as a freelancer. Mainly working on Ruby On Rails platform since 2010. This blog is about Ruby, Ruby On Rails and other subjects that I work. You can contact me here: Abhilash AK

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