Wednesday, 16 January 2013

Defining a String


Defining a String

There are many ways to define new strings:
STRING HANDLING 61
txt = "Episode XXXIV"
txt = 'Bart said: "Eat my shorts"'
txt = """Homer's face turned red. He replied: "Why you little!""""
The first line uses double quotes to enclose a string. This is the most
usual way to define a string. The second line uses single quotes. It comes
in handy if your string contains double quotes. The last line shows the last
resort – if the string contains both single and double quotes and possibly
line breaks, you can enclose the string in three sets of double quotes.
 Accessing Parts of a String
You can access individual characters with an index enclosed in square
brackets, in a similar way to lists. If you want to find the starting index of
a specific substring, use the function find(). For example, the following
code outputs first ‘h’ and then ‘i’:
txt = "python is great"
print txt[3]
print txt[txt.find("is")]
Above, txt.find("is") returns the value 7 and the character at
index 7 is ‘i’.
You can access substrings with the [start:end] notation:


txt = "python is great"
print txt[:6]
print txt[7:9]
print txt[10:]
The print statements output substrings ‘python ’, ‘is ’ and ‘great’.






No comments:

Post a Comment