Python tutorials :: python tutorials with strip - 24loader, Home of exclusive blog and update music and entertaiment

Python tutorials :: python tutorials with strip

<
strip
The strip method returns a string where whitespace on the left and right (but not internally)
has been stripped (removed):
>>> ' internal whitespace is kept '.strip()
'internal whitespace is kept'
As with lower, strip can be useful when comparing input to stored values. Let’s return to
the user name example from the section on lower, and let’s say that the user inadvertently
types a space after his name:
>>> names = ['gumby', 'smith', 'jones']
>>> name = 'gumby '
>>> if name in names: print 'Found it!'
...
>>> if name.strip() in names: print 'Found it!'
...
Found it!
>>>
You can also specify which characters are to be stripped, by listing them all in a string
parameter:
>>> '*** SPAM * for * everyone!!! ***'.strip(' *!')
'SPAM * for * everyone'
Stripping is performed only at the ends, so the internal asterisks are not removed.
In Appendix B: lstrip, rstrip.
translate
Similar to replace, translate replaces parts of a string, but unlike replace, translate works
only with single characters. Its strength lies in that it can perform several replacements simul￾taneously, and can do so more efficiently than replace.
There are quite a few rather technical uses for this method (such as translating newline
characters or other platform-dependent special characters), but let’s consider a simpler
(although slightly more silly) example. Let’s say you want to translate a plain English text into
one with a German accent. To do this, you must replace the character c with k, and s with z.
Before you can use translate, however, you must make a translation table. This transla￾tion table is a full listing of which characters should be replaced by which. Because this table
(which is actually just a string) has 256 entries, you won’t write it out yourself. Instead, you’ll
use the function maketrans from the string module.
The maketrans function takes two arguments: two strings of equal length, indicating that
each character in the first string should be replaced by the character in the same position in the
second string. Got that? In the case of our simple example, the code would look like the
following:
>>> from string import maketrans
>>> table = maketrans('cs', 'kz')
Once you have this table, you can use it as an argument to the translate method, thereby
translating your string:
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
An optional second argument can be supplied to translate, specifying letters that should
be deleted. If you wanted to emulate a really fast-talking German, for instance, you could
delete all the spaces:
>>> 'this is an incredible test'.translate(table, ' ')
'thizizaninkredibletezt'
See also: replace, lower.

No comments

Theme images by friztin. Powered by Blogger.
//]]>