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
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.
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.
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.
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.
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
string.
after importing the library, orfrom 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With