Wednesday, 16 January 2013

Making Decisions with a String


Making Decisions with a String

Often you need to make a decision based on a string. You can test
whether a string is non-empty as follows:
txt = ""
if txt:
print "Many characters!"
else:
print "No characters"
This example prints out ‘No characters’. You can find out the length
of a string with the function len(). The following example outputs
‘password too short’.
passwd = "secret"
if len(passwd) < 8:
print "password too short"
If you need to know whether a string contains a specific substring, use
the find() function. It returns −1 if the substring cannot be found.
url = "http://www.google.com"
if url.find(".com") == -1:
print "Access denied!"
If the substring should appear at the beginning of the string, use the
startswith() function:
if url.startswith("http://"):
print "This is a valid URL"

No comments:

Post a Comment