tags:

views:

93

answers:

4

What is the difference or relationship between str and string?

import string 
print str
print string 
+7  A: 

str is a built-in function (actually a class) which converts its argument to a string. string is a module which provides common string operations.

>>> str
<class 'str'>
>>> str(42)
'42'
>>> import string
>>> string
<module 'string' from '/usr/lib/python3.1/string.py'>
>>> string.digits
'0123456789'

Put another way, str objects are a textual representation of some object o, often created by calling str(o). These objects have certain methods defined on them. The module string provides additional functions and constants that are useful when working with strings.

Stephan202
A: 

"string" is a module that provides string handling functions, str is a built-in function that converts an object to a string representation. No relationship between the two.

Matthew Iselin
A: 

There is some overlap between the string module and the str type, mainly for historical reasons. In early versions of Python str objects did not have methods, so all string manipulation was done with functions from the string module. When methods were added to the str type (in Python 1.5?) the functions were left in the string module for compatibility, but now just forward to the equivalent str method.

However the string module also contains constants and functions that are not methods on str, such as formatting, character translation etc.

Dave Kirby
+3  A: 

Like Stephan202 said: str is a built in function which is just used to convert item into string. It has also many useful methods. For instance:

>>> str(100)
'100' # converts integer into string.

>>> str.lower('foobar')
'FOOBAR'

Now let's talk about String.-- It a python module which has very interesting functions. One of them Template thingy

>>> from string import  Template 
>>> t = Template('$foo is a test')
>>> t.substitute (foo='this')
'this is a test' # Replaces $foo variable with 'this'

There are other useful methods. Suppose you want all the ascii letters

>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
aatifh