python學習筆記(四)

一。文本

1.每次處理一個字符

     1)list

     2)import sets

               >>> import sets

               >>> magic_chars=sets.Set('adboieihoejoewjo')

               >>> enchar=sets.Set('eijowj')

               >>> ''.join(magic_chars & enchar)           #集合的交集

               'ijeow'

               >>>

2.字符和字符值之間的轉換

          >>> print ord(a)

          Traceback (most recent call last):

            File "<stdin>", line 1, in <module>

          NameError: name 'a' is not defined

          >>> print ord('a')

          97

          >>> print chr('99')

          Traceback (most recent call last):

            File "<stdin>", line 1, in <module>

          TypeError: an integer is required

          >>> print chr(99)

          c

          >>> print repr(str(99)

          ...

          ... )

          '99'

3.測試一個對象是否是類字符串

     >>> print isinstance(abc,basestring)

     Traceback (most recent call last):

       File "<stdin>", line 1, in <module>

     NameError: name 'abc' is not defined

     >>> print isinstance('abc',basestring)

     True

4.字符串對齊

     >>> 'abc'.center(20,'__')

     Traceback (most recent call last):

       File "<stdin>", line 1, in <module>

     TypeError: center() argument 2 must be char, not str

     >>>

     >>> print 'abc'.center(20,'__')

     Traceback (most recent call last):

       File "<stdin>", line 1, in <module>

     TypeError: center() argument 2 must be char, not str

     >>> 'abc'.center(20,'_')

     '________abc_________'

     >>>

     >>> 'aaa'.ljust(20,'@')

     'aaa@@@@@@@@@@@@@@@@@'

     >>> 'bbb'.rjust(20,'@')

     '@@@@@@@@@@@@@@@@@bbb'

     >>>

5.去除字符串兩端的空格

     >>> x='   p   '

     >>> x.ltrip()

     Traceback (most recent call last):

       File "<stdin>", line 1, in <module>

     AttributeError: 'str' object has no attribute 'ltrip'

     >>> x.lstrip()

     'p   '

     >>> x.rstrip()

     '   p'

     >>> x,strip()

     Traceback (most recent call last):

       File "<stdin>", line 1, in <module>

     NameError: name 'strip' is not defined

     >>> x.strip()

     'p'

     >>>

6.合併字符串

7.將字符串逐次反轉

     #正則匹配 匹配空格

     astring='Hello World'

     import re

     #split(r'()',string)

     rewords=re.split(r'(\s+)',astring)

     ' '.join(rewords)

8.檢查字符串中是否包含某字符集合中的字符

9.簡化字符串的translate的方法的使用

10.過濾字符串中不屬於指定集合的字符

11.python 的itertools


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章