If you have an integer that you would like to convert to a string, it is possible to do so using the str() function: >>> str(99999) '99999' To sort, we use the sort() method. Keep in mind that uppercase and lowercase sort differently, so you may wish to convert everything to lowercase or uppercase first. Here is how you sort a list: >>> superherolist = ["Batman", "Daredevil", "Adam Warlock"] >>> superherolist.sort() >>> superherolist ['Adam Warlock', 'Batman', 'Daredevil'] Let's try something a little more difficult: >>> alphabet = ['a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H','i','I', >>> alphabet.sort() >>> alphabet ['!', '#', '$', '%', '&', '(', ')', '*', '+', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '=', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '~'] Indexing and Slicing In addition to all the wonderful things that Python does to text, it also slices, it dices, it makes julienne fries! And if you act now, it even indexes. Remember that in Python, a string is basically an array. That is, each character has an index number, starting with zero. If I have a string with some names in it, and I know that say, the name I am looking for starts at index 0 and ends at index 10, I can return that portion of the string like so: >>> coolnames='Max Powers, Rod Thickington, Major Whoopass' >>> coolnames[0:10] 'Max Powers' I could of course leave off the 0 (or the starting index) if I wanted to and achieve the same result: >>> coolnames[:10] 'Max Powers' Say I just wanted the power part of the name; I could grab it like so: >>> coolnames[4:10] 'Powers' This is known as slicing. Indexing works in a similar way, only one character at a time: >>> coolnames[4] 'P' We can also use slicing to count backwards, as in the following: >>> coolnames[-4] 'p' >>> coolnames[-1] 's' >>> coolnames[-8] 'W' Or... >>> coolnames[-8:-1] 'Whoopas' Note that in the above method, the large number must come first. We can also use this to write our text backwards if we want to: >>> coolnames[::-1] 'ssapoohW rojaM ,notgnikcihT doR ,srewoP xaM' Well, that's all the time we have left at the moment. In our next article we will continue our discussion of Python String manipulation and maybe, just maybe, cover the rest of the string methods. So stay tuned! Till then...
blog comments powered by Disqus |
|
|
|
|
|
|
|