python “string” module?

柔情痞子 提交于 2019-12-05 05:18:56

The string module contains a set of useful constants, such as ascii_letters and digits, and the module is often still imported for that reason.

If you see a import string but never see string.something, someone just forgot to remove an unused import.

While there did use to be some things in string that are now standard methods of str objects, you still had to either

  1. prefix them with string. after importing the library, or
  2. use from string import <whatever> syntax.

Typically, the only times you'll see something properly imported but never "explicitly used" are from __future__ import with_statement or the like - the forwards/backwards compatability triggers used by Python for new language features.

well, in older versions the string module was indeed much more useful, but in the recent versions most of the string module functions are available also as string methods..

this page will give you a better look: http://effbot.org/librarybook/string.htm

Like Ambar said, it seems to be a redundant import, and RoeeeK is also right in saying that most of the string module's functions are meanwhile string methods, i.e. you can do "foobar".method() instead of string.function("foobar"). However, sometimes it is still useful to explicitely import the module; for instance, in the case of callbacks:

map(string.strip, [' foo ', ' bar ']).

Note that the above can also be achieved by [chunk.strip() for chunk in [' foo ', ' bar ']], so importing string is actually not required in this case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!