Published 2月 06, 2019 by with 0 comment

Automate The Boring Stuff With Python - Chapter 6 - 字符串操作




今天是看這本書Automate the Boring Stuff with Python(Python編程快速上手--讓繁瑣工作自動化)
第6章節(Manipulating Strings)所做的練習

這章主要講字符串的操作
在字符串開始的引號之前加上r, 可以使它成為原始字符
>>> print(r'That is Carol\'s cat.')
That is Carol\'s cat.

利用三重引號"""來做多行注釋
>>> """Comment1
Comment2
Comment3
"""

字符串的下標和切片
>>> spam = 'Hello world!'
>>> spam[0]
'H'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'

字符串的in和not in 操作符
>>> 'Hello' in 'Hello World!'
True
>>> 'hello' not in 'Hello World!'
True

upper(), lowper(), 可將字符轉換成大寫或小寫.
>>> spam = 'Hello World!'
>>> spam = spam.upper()
>>> spam
'HELLO WORLD!'
>>> spam = spam.lower()
>>> spam
'hello world!'

isupper(), islower() 可以檢查字符串是否全是大寫或小寫
>>> spam = 'HELLO'
>>> spam.isupper()
True
>>> spam = 'Hello'
>>> spam.islower()
False

isalpha(), 如果字符串只包含字母, 並非為空. 則返回True.
isalnum(), 如果字符串只包含字母和數字, 並非為空. 則返回True.
isdecimal(), 如果字符串只包含數字, 並非為空. 則返回True.
isspace(), 如果字符串只包含空格, 制符表和換行, 並非為空. 則返回True.
istitle(), 如果字符串只包含大寫字母開頭, 後面都是小寫字母. 則返回True.
>>> spam = 'hello'
>>> spam.isalpha()
True
>>> spam = 'Hello123'
>>> spam.isalnum()
True
>>> spam = '123'
>>> spam.isdecimal()
True
>>> spam = ' '
>>> spam.isspace()
True
>>> spam = 'Hello'
>>> spam.istitle()
True

startswith()和endswith(),  如果調用的字符串以該方法傳入的字符串的開始或結束, 則返回True.
>>> 'Hello World!'.startswith('Hello')
True
>>> 'Hello World!'.endswith('World!')
True

join(), 可將每個字符串連接起來.
split(), 反過來可將一串字符串分開
>>> '123'.join(['My', 'name', 'is', 'Peter'])
'My123name123is123Peter'
>>> 'My name is Peter'.split()
['My', 'name', 'is', 'Peter']

rjust()和ljust()和center(), 可以返回調用它們字符串填充版本.
第一個參數是一個整數長度, 第二個參數是指定填充字符.
>>> 'Hello'.rjust(20, '*')
'***************Hello'
>>> 'Hello'.ljust(20, '-')
'Hello---------------'
>>> 'Hello'.center(20, '#')
'#######Hello########'

strip(), rstrip(), lstrip(),可以刪除開頭及結尾, 右邊, 左邊的空白字符串
>>> ' Hello World! '.strip()
'Hello World!'
>>> ' Hello World! '.rstrip()
' Hello World!'
>>> ' Hello World! '.lstrip()
'Hello World! '


章節6習題, 用Notepad++打下列的程式碼,
另存為Chapter_6.py. 我附上中文注釋方便好讀.
# -*- coding: UTF-8 -*-
# http://juilin77.blogspot.com/
# v20190226
# Automate The Boring Stuff With Python - Chapter 6

# ========== 6.7 ==========
# 先定義出列表
tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

# 定義colwidth = tableData的長度為3 * [0] = [0, 0, 0]
colWidth = [0] * len(tableData)

# 找出colWidth列表中最大的值
for i in range(len(tableData)):
    for j in range(len(tableData[i])):
        if len(tableData[i][j]) > colWidth[i]:
            colWidth[i] = len(tableData[i][j])

# 把tableData 按照題目要求的順序印出來
for i in range(len(tableData[0])):
    for j in range(len(tableData)):
        print(tableData[j][i].rjust(colWidth[j], ' '), end=" ")
    print()

然後用Windows的cmd, 執行python.
D:\Tech\Blog\Python\Automate The Boring Stuff With Python>python Chapter_6.py
  apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose

D:\Tech\Blog\Python\Automate The Boring Stuff With Python>


完成

Reference:
Automate the Boring Stuff with Python
Python編程快速上手--讓繁瑣工作自動化
ISBN-10: B01N6B9BSA
https://www.amazon.com/Python%E7%BC%96%E7%A8%8B%E5%BF%AB%E9%80%9F%E4%B8%8A%E6%89%8B-%E8%AE%A9%E7%B9%81%E7%90%90%E5%B7%A5%E4%BD%9C%E8%87%AA%E5%8A%A8%E5%8C%96-%E7%BE%8E-Al-Sweigart%EF%BC%88%E6%96%AF%E7%BB%B4%E5%8A%A0%E7%89%B9%EF%BC%89/dp/B01I0XN8XY/ref=sr_1_1?ie=UTF8&qid=1543814481&sr=8-1&keywords=9787115422699

官網:
https://automatetheboringstuff.com/

最初發表 / 最後更新: 2019.02.06 / 2019.02.06

0 comments:

張貼留言