Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources] - نسخه متنی

David Ascher, Alex Martelli, Anna Ravenscroft

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید


Recipe 1.7. Reversing a String by Words or Characters


Credit: Alex Martelli


Problem


You want to reverse the characters or words in a string.


Solution


Strings are immutable, so, to reverse one, we need to make a copy.
The simplest approach for reversing is to take an extended slice with
a "step" of -1, so that the slicing
proceeds backwards:

revchars = astring[::-1]

To flip words, we need to make a list of words, reverse it, and join
it back into a string with a space as the joiner:

revwords = astring.split( )     # string -> list of words
revwords.reverse( ) # reverse the list in place
revwords = ' '.join(revwords) # list of strings -> string

or, if you prefer terse and compact
"one-liners":

revwords = ' '.join(astring.split( )[::-1])

If you need to reverse by words while preserving untouched the
intermediate whitespace, you can split by a regular expression:

import re
revwords = re.split(r'(\s+)', astring)# separators too, since '(...)'
revwords.reverse( ) # reverse the list in place
revwords = ''.join(revwords) # list of strings -> string

Note that the joiner must be the empty string in this case, because
the whitespace separators are kept in the revwords
list (by using re.split with a regular expression
that includes a parenthesized group). Again, you could make a
one-liner, if you wished:

revwords = ''.join(re.split(r'(\s+)', astring)[::-1])

but this is getting too dense and unreadable to be good Python code!


Discussion


In Python 2.4, you may make the by-word one-liners more readable by
using the new built-in function reversed instead
of the less readable extended-slicing indicator
[::-1]:

revwords = ' '.join(reversed(astring.split( )))
revwords = ''.join(reversed(re.split(r'(\s+)', astring)))

For the by-character case, though, astring[::-1]
remains best, even in 2.4, because to use
reversed, you'd have to introduce
a call to ''.join as well:

revchars = ''.join(reversed(astring))

The new reversed built-in returns an
iterator, suitable for looping on or for passing
to some "accumulator" callable such
as ''.joinit does not return a ready-made
string!


See Also


Library Reference and Python in a
Nutshell
docs on sequence types and slicing, and (2.4
only) the reversed built-in; Perl
Cookbook
recipe 1.6.

/ 394