12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

S = 'spam'>>> S.upper( ) # Upper- and lowercase conversions'SPAM'>>> S.isalpha( ) # Content tests: isalpha, isdigit, etc.True>>> line = 'aaa,bbb,ccccc,dd\n'>>> line = line.rstrip( ) # Remove whitespace characters on the right side>>> line'aaa,bbb,ccccc,dd'One note here: although sequence operations are generic, methods are not—stringmethod operations work only on strings, and nothing else. As a rule of thumb,<strong>Python</strong>’s toolset is layered: generic operations that span multiple types show up asbuilt-in functions or expressions (e.g., len(X), X[0]), but type-specific operations aremethod calls (e.g., aString.upper( )). Finding the tools you need among all these categorieswill become more natural as you use <strong>Python</strong> more, but the next section givesa few tips you can use right now.Getting HelpThe methods introduced in the prior section are a representative, but small, sampleof what is available for string objects. In general, this book is not exhaustive in itslook at object methods. For more details, you can always call the built-in dir function,which returns a list of all the attributes available in a given object. Becausemethods are function attributes, they will show up in this list:>>> dir(S)['_ _add_ _', '_ _class_ _', '_ _contains_ _', '_ _delattr_ _', '_ _doc_ _', '_ _eq_ _','_ _ge_ _', '_ _getattribute_ _', '_ _getitem_ _', '_ _getnewargs_ _', '_ _getslice_ _','_ _gt_ _', '_ _hash_ _', '_ _init_ _', '_ _le_ _', '_ _len_ _', '_ _lt_ _', '_ _mod_ _','_ _mul_ _', '_ _ne_ _', '_ _new_ _', '_ _reduce_ _', '_ _reduce_ex_ _', '_ _repr_ _','_ _rmod_ _', '_ _rmul_ _', '_ _setattr_ _', '_ _str_ _', 'capitalize', 'center','count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index','isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper','join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex','rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith','strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']You probably won’t care about the names with underscores in this list until later inthe book, when we study operator overloading in classes—they represent the implementationof the string object, and are available to support customization. Ingeneral, leading and trailing double underscores is the naming pattern <strong>Python</strong> usesfor implementation details. The names without the underscores in this list are thecallable methods on string objects.Strings | 73

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!