Operations on String & some Simple Program Scripts




How to declare a string:

>>> myString = "We are learning" #double quotes are necessary
>>> myStr2 = 'Python' #even a single quote can be used
>>> print myString #print a Python in-built function
We are learning
>>> myString
'We are learning' #single quote indicates that variable myString is a string
>>> myStr2
'Python'


Operations on String:

>>> print myString + myStr2
We are learningPython
>>> print myString + ' ' + myStr2
We are learning Python
>>> print myString, myStr2 #comma leaves a space between them
We are learning Python
>>> 3*'x'
'xxx'
>>> 'x'+'x'
'xx'
>>> 'x'+str(3) #note that 3 is converted to string by Type Casting
'x3'
>>> len('xyz') #len() in Python in-built that returns the length of string or list
3

Extracting Parts of String:

>>> s = 'xyz'
>>> s[0] # its called indexing
'x'
>>> s[1]
'y'
>>> s[2]
'z'
>>> s[-1]
'z'
>>> s[-2]
'y'
>>> s[-3]
'x'
>>> s[1:3]  # its called Slicing. Explained below
'yz'

s[a:b] will start from s[a] & prints upto s[b-1]..so here it prints from s[1] to s[2]

Taking Input from User:

>>> name = raw_input('Enter your name: ')
#as soon as I run above line it shows following text
Enter your name:
#Now When I type my name & press Enter
Enter your name: Ravi Ojha
>>> name
'Ravi Ojha'

Related Articles:
Python Objects: What are Tuples and Indexing & Slicing of Tuples
Python Objects: Dictionary (dict)
Lists and Mutation of Lists with examples
Note:
This is a part of what I learn in an online Open Course Ware offered by MIT on edX
Its for my personal reference & also for those who have missed the course.
You too can enroll yourself on edX (if they are still offering the course MITx 6.00x