Friday, 4 December 2015

Strings in python


String is a sequence of character specified in single quotes('…'), double quotes("…"), (or) triple quotes ("""…"""  or '''… '''). Strings in python are immutable, i.e., an object with a fixed value.
>>> str1='Hello World'
>>> str2="Hello World"
>>> str3="""Hello
... World
... """
>>> str1
'Hello World'
>>> str2
'Hello World'
>>> str3
'Hello\nWorld\n'


Special characters are escaped with backslash.
>>> message='He don\'t know about this'
>>> message
"He don't know about this"


‘print’ method treat characters preceded by \ (backslash) as special characters.

>>> print('firstline\nsecondline')
firstline
secondline


As you observe output, \n prints new line. If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote

>>> print(r'firstline\nsecondline')
firstline\nsecondline


Concatenate strings
'+' operator is used to concatenate strings.

>>> hello="Hello,"
>>> message="How are you"
>>> info=hello+message
>>> info
'Hello,How are you'


Two or more string literals next to each other are automatically concatenated.

>>> 'Hello' "How" 'are' 'you'
'HelloHowareyou'


Repeat strings
By using ‘*’, we can repeat the strings.

>>> 'hi'*2
'hihi'
>>> 'hi'*2+'hello'*3
'hihihellohellohello'


Access specific character from strings
You can access, specific character of string using index position.

>>> name="Hello World"
>>> name[0]
'H'
>>> name[6]
'W'


Index 0 represents 1st character, 1 represents 2nd character etc.,

You can also use negative numbers for indexing.

-1 represents last character; -2 represents second-last character etc.,

>>> name
'Hello World'
>>> name[-1]
'd'
>>> name[-2]
'l'
>>> name[-7]
'o'


Slicing
Slicing is used to get sub string of given string.

Example
Description
string[start:end]
Returns sub string from index start (included) to end index (excluded).
string[:end]
Returns sub string from index 0(included) to end index (excluded).
string[start:]
Return sub string from index start to till end.
string[-2:]
Return characters from 2nd last to end.


>>> message="Hello World"
>>> 
>>> message[0:5]
'Hello'
>>> message[5:]
' World'
>>> message[:]
'Hello World'
>>> message[-2:]
'ld'
>>> message[-5:-2]
'Wor'


Get length of the string
Function ‘len(str)’ is used to get the length of the string.    
>>> message
'Hello World'
>>> len(message)
11
>>> len("How are you")
11










Previous                                                 Next                                                 Home

No comments:

Post a Comment