Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

string.something
like image 329
johnny Avatar asked Sep 10 '11 07:09

johnny


People also ask

What is string module in Python?

Python string module contains a single utility function - capwords(s, sep=None). This function split the specified string into words using str. split(). Then it capitalizes each word using str. capitalize() function.

What is the use of the string module?

Three functions are provided in the string module for removing whitespace from strings: lstrip, rstrip and strip which removing leading, trailing and both leading and trailing whitespace from a string, respectively. Each of the functions accepts a string and returns the stripped string.

Do I need to import string in Python?

Generally you don't need to import string module as the class is already in builtins. However, there are several constants that are in the string module that are not built in, that can be usefull.

How do you include a string in Python?

Python add strings with + operator The easiest way of concatenating strings is to use the + or the += operator. The + operator is used both for adding numbers and strings; in programming we say that the operator is overloaded. Two strings are added using the + operator.


2 Answers

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.

like image 179
Carl Smith Avatar answered Oct 05 '22 00:10

Carl Smith


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 image 34
Amber Avatar answered Oct 04 '22 23:10

Amber