官术网_书友最值得收藏!

  • The Python Apprentice
  • Robert Smallshire Austin Bingham
  • 407字
  • 2021-07-02 22:16:57

String methods

The String objects also support a wide variety of operations implemented as methods. We can list those methods by using help() on the string type:

>>> help(str)

When you press Enter, you should see a display like this:

Help on class str in module builtins:

class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
:

On any platform you can browse through the help page by pressing the spacebar to advance one page at a time until you see the documentation for the capitalize() method, skipping over all the methods that begin and end with double underscores:

 |      Create and return a new object.  See help(type) for accurate    
| signature.

|
| __repr__(self, /)
| Return repr(self).
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return self*value.
|
| __sizeof__(...)
| S.__sizeof__() -> size of S in memory, in bytes
|
| __str__(self, /)
| Return str(self).
|
| capitalize(...)
| S.capitalize() -> str
|
| Return a capitalized version of S, i.e. make the first
| character
have upper case and the rest lower case.
|
:

Press Q to quit the help browser, and we'll try to use captialize(). Let's make a string that deserves capitalization – the name of a capital city no less!

>>> c = "oslo"

To call methods on objects in Python we use the dot after the object name and before the method name. Methods are functions, so we must use the parentheses to indicate that the method should be called.

>>> c.capitalize()
'Oslo'

Remember that strings are immutable, so the capitalize() method didn't modify c in place. Rather, it returned a new string. We can verify this, by displaying c, which remains unchanged:

>>> c
'oslo'

You might like to spend a little time familiarizing yourself with the various useful methods provided by the string type by browsing the help.

主站蜘蛛池模板: 乐平市| 县级市| 西乌珠穆沁旗| 马鞍山市| 九台市| 明溪县| 十堰市| 通榆县| 武川县| 赣州市| 清苑县| 乌鲁木齐县| 都昌县| 阿拉善左旗| 噶尔县| 双柏县| 喀喇| 揭西县| 贵定县| 云浮市| 建昌县| 寿宁县| 阳泉市| 德安县| 多伦县| 长顺县| 绥德县| 商河县| 霞浦县| 滁州市| 左贡县| 曲周县| 五华县| 香河县| 闵行区| 革吉县| 中西区| 绥德县| 章丘市| 济源市| 六安市|