开发者

python "string" module?

So I'm reading this old module from I think around 2002 and it has this line "import string". Did Python require you to import a string module explicitly before to be able to use开发者_StackOverflow社区 string type variables or something? I don't see it used like this in the code:

string.something


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜