Python编程快速上手-让繁琐工作自动化 — 读书与代码笔记

chapter6

# -*- coding:utf-8 -*-
# @FileName     :chapter6_string.py
# @Time         :2020/8/16 11:44
# @Author       :Wu Hongyi
# @Copyright    :Wu Hongyi
# Function description:
'''
本文件为Python编程快速上手-让繁琐工作自动化一书的第六章示例练习代码

'''
# @version      :Version1.0
# Modification description:
'''

'''

# 处理字符串
# 单双引号合理使用以规避字符串提前结束问题
spam = "That is Alice's cat."

# 如果在字符串中既需要使用单引号又需要使用双引号,那就要使用转义字符
# 转义字符包含一个倒斜杠(\),紧跟着是想要添加到字符串中的字符。(尽管它包含两个字符,
# 但大家公认它是一个转义字符。)例如,单引号的转义字符是\’。你可以在单引号开始和结束的字符串中使用它。
spam = 'Say hi to Bob\'s mother.'
print("\\Hello there!\nHow are you?\tI\'m doing fine.")

# 原始字符串
# 可以在字符串开始的引号之前加上r,使它成为原始字符串。“原始字符串”完全忽略所有的转义字符,
# 打印出字符串中所有的倒斜杠。因为这是原始字符串,Python认为倒斜杠是字符串的一部分,而不是
# 转义字符的开始。如果输入的字符串包含许多倒斜杠,比如下一章中要介绍的正则表达式字符串,那么
# 原始字符串就很有用。
print(r'That is Carol\'s cat.')

# 用三重引号的多行字符串
# 多行字符串的起止是3个单引号或3个双引号,“三重引号”之间的所有引号、制表符或换行,都被认为是字符串的一部分
# Python的代码块缩进规则不适用于多行字符串
print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')

print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat burglary, and extortion.\n\nSincerely,\nBob')

# 多行注释
# 虽然井号字符(#)表示这一行是注释,但多行字符串常常用作多行注释。
# 下面是完全有效的Python代码
"""This is a test Python program.
Written by Al Sweigart al@inventwithpython.com
This program was designed for Python 3, not Python 2.
"""
def spam():
    """This is a multiline comment to help
    explain what the spam() function does."""
    print('Hello!')

# 字符串下标和切片
# 字符串和列表一样,可用下标和切片。
# 如果指定一个下标,将得到字符串在该处的字符。如果用一个下标和另一个下标指定一个范围,
# 开始下标将被包含,结束下标则不包含
# 注意:字符串切片并没有修改原来的字符串。可以从一个变量中获取切片,记录在另一个变量中
spam = 'Hello world!'
fizz = spam[0:5]
fizz

# 字符串的in和not in操作符
# 如列表一样,in和not in操作符也可以用于字符串。用in或not in连接两个字符串得到的表达式,
# 将求值为布尔值True或False。
'Hello' in 'Hello world!'
'Hello' in 'Hello'
'HEllo' in 'Hello world'
'' in 'spam'     # 结束符在每个字符串末尾都有
'cats' not in 'cats and dogs'
# 这些表达式测试第一个字符串(精确匹配,区分大小写)是否在第二个字符串中

# 有用的字符串方法
# 字符串方法upper()、lower()、title()、isupper()和islower()
# upper()和lower()字符串方法返回一个新字符串,其中原字符串的所有字母都被相应地转换为大写或小写。
# 字符串中非字母字符保持不变。
spam = 'Hello world!'
spam = spam.upper()
spam
spam = spam.lower()
spam
spam = spam.title()
spam
# 注意:,这些方法没有改变字符串本身,而是返回一个新字符串。如果希望改变原来的字符串,
# 就必须在该字符串上调用upper()或lower(),然后将这个新字符串赋给保存原来字符串的变量。
# 需要进行大小写无关的比较,upper()和lower()方法就很有用。字符串'great'和'GREat'彼此不相等。
# 但在下面的小程序中,用户输入Great、GREAT或grEAT都没关系,因为字符串首先被转换成小写
print('How are you?')
feeling = input()
if feeling.lower() == 'great':
    print('I feel great too.')
else:
    print('I hope the rest of your day is good.')

# 如果字符串至少有一个字母,并且所有字母都是大写或小写,
# isupper()和islower()方法就会相应地返回布尔值True。否则,该方法返回False
spam = 'Hello World!'
spam.islower()
spam.isupper()
spam.istitle()     # 要求每个单词首字母大写
'HELLO'.isupper()
'abc12345'.islower()
'12345'.islower()
'12345'.isupper()

# 因为upper()和lower()字符串方法本身返回字符串,所以也可以在“那些”返回的字符串上继续调用字符串方法。
# 这样做的表达式看起来就像方法调用链。
'Hello'.upper()
'Hello'.upper().lower()
'Hello'.upper().lower().upper()
'HELLO'.lower()
'HELLO'.lower().islower()

# isX字符串方法
# 除了islower()和isupper(),还有几个字符串方法,它们的名字以is开始。
# 这些方法返回一个布尔值,描述来字符串的特点、
# isalpha()返回True,如果字符串只包含字母,并且非空;
# isalnum()返回True,如果字符串只包含字母和数字,并且非空;
# isdecimal()返回True,如果字符串只包含数字字符,并且非空;
# isspace()返回True,如果字符串只包含空格、制表符和换行,并且非空;
# istitle()返回True,如果字符串仅包含以大写字母开头、后面都是小写字母的单词。
'hello'.isalpha()
'hello123'.isalpha()
'hello123'.isalnum()
'hello'.isalnum()
'123'.isdecimal()
' '.isspace()
'This Is Title Case'.istitle()
'This Is Title Case 123'.istitle()
'This Is not Title Case'.istitle()
'This Is NOT Title Case Either'.istitle()   # 只能是每个单词第一个字母大写,其他小写

# 要验证用户输入,isX字符串方法是有用的
# validateInput.py
while True:
    print('Enter your age:')
    age = input()
    if age.isdecimal():
        break
    print('Please enter a number for your age.')
while True:
    print('Select a new password (letters and numbers only):')
    password = input()
    if password.isalnum():
        break
    print('Passwords can only have letters and numbers.')

# 字符串方法startswith()和endswith()
# startswith()和endswith()方法返回True,如果它们所调用的字符串以该方法传入的字符串开始或结束。
# 否则,方法返回False。
'Hello world!'.startswith('Hello')
'Hello world!'.endswith('world!')
'abc123'.startswith('abcdef')
'abc123'.endswith('12')
'Hello world!'.startswith('Hello world!')
'Hello world!'.endswith('Hello world!')
# 如果只需要检查字符串的开使或结束部分是否等于另一个字符串,而不是整个字符串,
# 这些方法就可以替代等于操作符==,这很有用

# 字符串方法join()和split()
# join()方法在一个字符串上调用,参数是一个字符串列表,返回一个字符串。返回的字符串由传入的列表中每个字符串连接而成
', '.join(['cats', 'rats', 'bats'])
' '.join(['My', 'name', 'is', 'Simon'])
'ABC'.join(['My', 'name', 'is', 'Simon'])
# 调用join()方法的字符串,被插入到列表参数中每个字符串的中间
# 记住:join()方法是针对一个字符串而调用的,并且传入一个列表值(很容易不小心用其他的方式调用它)

# split()方法做的事情正好与join()方法相反:针对一个字符串进行调用,返回一个字符串列表
'My name is Simon'.split()
# 默认情况下,字符串'My name is Simon'按照各种空白字符分割,诸如空格、制表符或换行符。这些空白字符不包含在返回列表的字符串中。
# 也可以向split()方法传入一个分割字符串,指定它按照不同的字符串分割
'MyABCnameABCisABCSimon'.split('ABC')
'My name is Simon'.split('m')

# 常见的split()用法,是按照换行符分割多行字符串
spam = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment".
Please do not drink it.
Sincerely,
Bob'''
spam.split('\n')

# 用rjust()、ljust()和center()方法对齐文本
# rjust()和ljust()字符串方法返回调用它们的字符串的填充版本,通过插入空格来对齐文本。
# 这两个方法的第一个参数是一个整数长度,用于对齐字符串。
'Hello'.rjust(10)
'Hello'.rjust(20)
'Hello World'.rjust(20)
'Hello'.ljust(10)

# rjust()和ljust()方法的第二个可选参数将指定一个填充字符,取代空格字符
'Hello'.rjust(20, '*')
'Hello'.ljust(20, '-')

# center()字符串方法与ljust()和rjust()类似,但它让文本居中,而不是左对齐或右对齐。
'Hello'.center(20)
'Hello'.center(20, '=')

# 如果需要打印表格式数据,留出正确的空格,这些方法就特别有用
# picnicTable.py
def printPicnic(itemsDict, leftWidth, rightWidth):
    print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
    for k, v in itemsDict.items():
        print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 12, 5)
printPicnic(picnicItems, 20, 6)
# 利用rjust()、ljust()和center()让你确保字符串整齐对齐,即使你不清楚字符串有多少字符

# 用strip()、rstrip()和lstrip()删除空白字符
# 有时候希望删除字符串左、右或两边的空白字符(空格、制表符和换行符)。strip()字符串方法将返回一个新的字符串,
# 它的开头或末尾都没有空白字符。lstrip()和rstrip()方法将相应删除左或右的空白字符。
spam = ' Hello World '
spam.strip()
spam.lstrip()
spam.rstrip()
# 有一个可选的字符串参数,指定两边的哪些字符应该删除
spam = 'SpamSpamBaconSpamEggsSpamSpam'
spam.strip('ampS')
# 向strip()方法传入参数'ampS',告诉它在变量中存储的字符串两端,删除出现的a、m、p和大写的S。
# 传入strip()方法的字符串中,字符的顺序并不重要:strip('ampS')做的事情和strip('mapS')或strip('Spam')一样。

# 用pyperclip模块拷贝粘贴字符串
# pyperclip模块有copy()和paste()函数,可以向计算机的剪贴板发送文本,或从它接收文本。
# 将程序的输出发送到剪贴板,使它很容易粘贴到邮件、文字处理程序或其他软件中。
# 注:pyperclip模块不是Python自带的,可以用pip install pyperclip安装
import pyperclip
pyperclip.copy('Hello world!')
pyperclip.paste()
# 如果程序之外的某个程序改变了剪贴板的内容,paste()函数就会返回它

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值