Wednesday, September 14, 2011

Working with Strings

In Python, strings can be represented in several ways:

With single quotes: 'Here is a string'

With double quotes: "Here is a very similar string"
With triple double quotes: """ Here is a very long string that can
if we wish span several lines and Python will
preserve the lines as we type them..."""
One special use of the latter form is to build in documentation for Python functions that we create ourselves - we'll see this later.

We can access the individual characters in a string by treating it as an array of characters. There are also usually some operations provided by the programming language to help
us manipulate strings - find a sub string, join two strings, copy one to another etc.

String operators

Operator Description
S1 + S2 Concatenation of S1 and S2
S1 * N N repetitions of S1


now lets create an example using the above mentioned string operators:

StringOperators.py
-------------------------
s1=' again'
s2= ' and again'
print (s1+ s2 ) # string concatenation

print (s1 * 3) # string repetition
print(' Again ' + (' and again' * 3) )
print(s1+(s2*3))


output:
again and again
again again again
Again and again and again and again
again and again and again and again


Notice that the last two examples produced the same output.

No comments:

Post a Comment