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.5. Trimming Space from the Ends of a String


Credit: Luther Blissett


Problem


You need to work on a string
without regard for any extra leading or trailing spaces a user may
have typed.


Solution




That's what the
lstrip, rstrip, and
strip methods of string objects are for. Each
takes no argument and returns a copy of the starting string, shorn of
whitespace on either or both sides:

>>> x = '    hej   '
>>> print '|', x.lstrip( ), '|', x.rstrip( ), '|', x.strip( ), '|'
| hej | hej | hej |


Discussion



Just as you may need to add space to
either end of a string to align that string left, right, or center in
a field of fixed width (as covered previously in Recipe 1.4), so may you need to remove
all whitespace (blanks, tabs, newlines, etc.) from either or both
ends. Because this need is frequent, Python string objects supply
this functionality through three of their many methods. Optionally,
you may call each of these methods with an argument, a string
composed of all the characters you want to trim from either or both
ends instead of trimming whitespace characters:

>>> x = 'xyxxyy hejyx  yyx'
>>> print '|'+x.strip('xy')+'|'
| hejyx |

Note that in these cases the leading and trailing spaces have been
left in the resulting string, as have the 'yx'
that are followed by spaces: only all the occurrences of
'x' and 'y' at
either end of the string have been removed from the resulting string.


See Also


The Library Reference section on string
methods; Recipe 1.4;
Java Cookbook recipe 3.12.


/ 394