#this program illustrates many of the basic features of #strings in Python. def stringstuff(): #you can define constant strings #using either single, double, or triple #quotes (useful if you include line breaks #in strings), and assign them to variables. s="hello" t='goodbye' u="""See you later""" print s print t print u #You can also use special sequences to #indicate nonprinting characters like #tabs and newlines v="\nso much depends\nupon\n\na red wheel\nbarrow\n\nglazed with rain\nwater\n\nbeside the white\nchickens\n\n" print v #You can concatenate strings with + print s+"\t"+t #What if you wanted to actually have backslashes in the string? w="This is a string\\nwith a backslash in it" print w print "\n\n" # # # #We can also read a string from the keyboard x=raw_input("Enter your own string here") print x print "\n\n" # #Here is how to find the length of a string: print len(s) print len(u) # #There is an empty string! e="" print "The length of the empty string is\t",len(e),"\n\n\n" #You can loop through a string with the for statement for c in s: print c print"\n\n\n" # # # # #You can use the ord function to get the ASCII code for a character print "The ASCII code for 'A' is ", ord("A") print "\n\n" for c in u: print ord(c) #You can use chr to invert ord print "\n\nThe character whose ASCII code is 87 is ", chr(87) print "\n\n" #We can refer to the individual characters in the string using #bracket notation print "cell 0 of s contains", s[0] print "cell 1 of s contains", s[1] #This one will cause an error, so we comment it out! #print "cell 5 of s contains", s[5] print "\n\n" #We can use negative indices print "cell -1 of s contains", s[-1] print "\n\n" #We can also extract various substrings: a=s[1:4] b=s[1:5] c=s[:4] d=s[1:] e=s[:-1] f=s[-2:] print a print b print c print d print e print f print"\n\n" #We can use the operator in as part of logical expressions if "ood" in t: print "'ood' appears in 'goodbye'" print "\n\n" #You CAN'T do this: #s[3]='M' #Instead you have to write s=s[0:3]+'M'+s[4:] print s