python “string” module?

2019-04-24 10:09发布

问题:

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 string type variables or something? I don't see it used like this in the code:

string.something

回答1:

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.



回答2:

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.



回答3:

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



回答4:

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.