2016年7月18日 星期一

Python 的字串與串列(一)

字串基本認知:
  • Python3 支援 Unicode 標準,可容納任何語言文字!
  • Python 的字元是不可變的!
  • 字串:字元一個一個串起來的結果!
  • Python 處理字串常用函數:
    函數名稱說明
    str()將資料類型轉換成字串
    print()在螢幕上列出內容
    len()計算字元長度
    split()利用特定分隔符號來分解字串
    join()結合字串
    strip()修剪兩端的字元
    capitalize()第一個字母改成大寫
    title()每個字的第一個字元改成大寫
    upper()所有字元改成大寫
    lower()所有字元改成小寫
    swapcase()大小寫互換
    center()置中字串
    ljust()靠左對齊
    rjust()靠右對齊
    replace()置換字串
    \跳脫字元設定
    \n換行
    \t空出一個間隔來對齊文字
    +結合字串
    *複製字串
    []擷取字元
    [開始:結束:間隔]擷取字串中的某一段字元組

快速測試:
  1. 使用互動式指令:
    #python3
    Python 3.4.3 (default, Jan 26 2016, 02:25:35)
    [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
    
  2. 字串練習:
    >>> str(123)
    '123'
    >>> abc = "Hello,\n This is a book!,\n"
    >>> print(abc)
    Hello,
     This is a book!,
    
    >>> deg = "He is a boy,\t and She is a girl!\t"
    >>> print(abc+deg)
    Hello,
     This is a book!,
    He is a boy,     and She is a girl!
    >>> abc[5]
    ','
    >>> abc[15]
    ' '
    >>> abc[8]
    'T'
    >>> abc[3:15:2]
    'l, hsi'
    >>> abc[-3]
    '!'
    >>> len(abc)
    25
    >>> abc.title()
    'Hello,\n This Is A Book!,\n'
    >>> abc.upper()
    'HELLO,\n THIS IS A BOOK!,\n'
    >>> abc.lower().capitalize()
    'Hello,\n this is a book!,\n'
    >>> abc.swapcase()
    'hELLO,\n tHIS IS A BOOK!,\n'
    >>> abc.center(50)
    '            Hello,\n This is a book!,\n             '
    >>> abc.ljust(50)
    'Hello,\n This is a book!,\n                         '
    >>> abc.rjust(50)
    '                         Hello,\n This is a book!,\n'
    >>> abc.replace('book','pen')
    'Hello,\n This is a pen!,\n'