Python "string" module?

So, I am reading this old module, I think, around 2002, and it has this line "import string". Did Python require you to explicitly import the string module in order to be able to use variables like strings or something else? I do not see this being used in the code:

string.something 
+5
source share
4 answers

If you see import string but never see string.something , someone just forgot to delete the unused import.

Although string used some things that are now standard methods of str objects, you still had to either

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

Typically, the only times when you see something properly imported but never "explicitly used" are from __future__ import with_statement or the like - redirect / backward compatibility triggers used by Python for new language functions.

+2
source

The string module contains a set of useful constants , for example ascii_letters and digits , and the module is often imported for this reason.

+1
source

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

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

0
source

As Barn said, this is apparently a redundant import, and RoeeeK is also right in saying that most of the functions of the string module are in the meantime string methods, i.e. you can do "foobar".method() instead of string.function("foobar") . However, sometimes it is still useful to explicitly import the module; for example in case of callbacks:

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

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

-1
source

All Articles