基于網(wǎng)絡(luò)課程《Python全棧開發(fā)專題》 記錄筆記累颂,請(qǐng)支持正版課程省容。
字符串格式化
%
的使用
# %s 代表字符串的占位符
formatStr = 'Are you %s? I\'m %s.'
values = ('OK', 'XiaoMing')
print(formatStr % values)
# %f 浮點(diǎn)數(shù)
# %d 整數(shù)
from math import pi;
# formatStr = 'PI是圓周率,PI的值是:%f'
formatStr = 'PI是圓周率,PI的值是:%.2f (保留小數(shù)點(diǎn)后%d位)'
values = (pi, 2)
print(formatStr % values)
# %轉(zhuǎn)義: %%
formatStr = '降水概率%d%%'
values = (57)
print(formatStr % values)
用Template類格式化字符串
from string import Template
template1 = Template('$lang是一種編程語言硝桩,$lang很容易學(xué)習(xí),給你打$score分枚荣。')
# 用命令參數(shù)傳入
print(template1.substitute(lang='Python', score=100))
# 可以使用${}
template2 = Template('${s}stitute')
print(template2.substitute(s='sub'))
# 轉(zhuǎn)義:$$
template3 = Template('$dollar$$相當(dāng)于多少$pounds英鎊')
print(template3.substitute(dollar=20, pounds=25))
# 也可以傳入字典
template4 = Template('姓別$sex碗脊,愛好$like')
data = {}
data['sex'] = '男'
data['like'] = '女'
print(data)
print(template4.substitute(data))
使用format格式化字符串
# 匿名,按順序傳參
s1 = '今天是 {}, 溫度{}橄妆。'
print(s1.format('星期三', '24攝氏度'))
# 使用命名參數(shù)傳參
s2 = '今天是 {week}, 溫度{x}衙伶。'
print(s2.format(week = '星期三', x = '26度'))
# 匿名和命名的混用
s3 = '一{}, 二{two}, 三{three}, 四{}'
# 把所有匿名的放在前面,命名的隨便寫
print(s3.format(1, 4, two=2, three=3))
# 使用序號(hào)格式化參數(shù)
s4 = '一{1}, 二{two}, 三{0}, 四{four}'
print(s4.format(3, 1, two=2, four=4))
# 獲取列表中的指定值
nums = [1, 2, 3, 4]
s5 = '一{nums[0]}, 二{nums[1]}, 三{nums[2]}, 四{nums[3]}'
print(s5.format(nums=nums))
# 使用屬性
import math
s6 = 'The {mod.__name__} module defines the vlaue for {mod.pi}'
print(s6.format(mod=math))
format字符串格式化類型符
- a 將字符串按unicode編碼輸出
- b 將一個(gè)整數(shù)格式化為一個(gè)二進(jìn)制數(shù)
- c ASCII
- d 十進(jìn)制
- e/E 科學(xué)計(jì)數(shù)法
- f/F 浮點(diǎn)數(shù)
- g/G 會(huì)根據(jù)整數(shù)時(shí)的位數(shù)在浮點(diǎn)數(shù)和科學(xué)計(jì)數(shù)法之間切換害碾,在整數(shù)位超過6位時(shí)與E相同矢劲,否則與F相同
- o 八進(jìn)制
- s 按原樣格式化字符串
- x/X 十六進(jìn)制(大小寫字母)
- % 百分比
s1 = '原樣輸出: {first!s}; 調(diào)用repr函數(shù): {first!r} 輸出Unicode:{first!a}'
print(s1.format(first="中"))
# 將一個(gè)整數(shù)按浮點(diǎn)數(shù)格式輸出
s2 = '整數(shù):{num}慌随; 浮點(diǎn)數(shù): {num:f}'
print(s2.format(num=5))
# 進(jìn)制轉(zhuǎn)換
s3 = '十進(jìn)制:{num}; 二進(jìn)制:{num:b}; 八進(jìn)制:{num:o}; 十六進(jìn)制:{num:x}'
print(s3.format(num=128))
# 科學(xué)計(jì)數(shù)法
s4 = '科學(xué)計(jì)數(shù)法:{num:e}'
print(s4.format(num = 678980000000000000))
# 浮點(diǎn)數(shù)按百分比輸出
s5 = '百分比:{num:%}'
print(s5.format(num=0.3478)) # 34.780000%
s5 = '百分比:{num:.1%}'
print(s5.format(num=0.3478)) # 34.8%
format 字段寬度芬沉、精度、千位分隔符
# 固定寬度
print("a:{num:12}".format(num = 32))
print("a:{num:<12}".format(num = 32))
print("a:{num:^12}".format(num = 32))
# create table
print("{header1:8}{header2:5}".format(header1='姓名', header2='年齡'))
print("{cell11:8}{cell12:5}".format(cell11='張三', cell12=18))
print("{cell21:8}{cell22:5}".format(cell21='李四', cell22=23))
print("{cell31:8}{cell32:5}".format(cell31='二狗', cell32=27))
# 精度
from math import pi
import math
print('float number: {pi:.2f}'.format(pi=pi))
print('float number: {obj.pi:.2f}'.format(obj=math))
print('float number: {pi: 20.4f}'.format(pi = pi))
# 截取字符串
print('{msg:.5}'.format(msg='hello world')) # 截取前5個(gè)字符
# 千位分隔符
print('GooGol is {:,}: '.format(10 ** 100))
對(duì)齊和填充
from math import pi
print('{pi:012.3f}'.format(pi = pi)) # 00000003.142
print('{pi:0>12.3f}'.format(pi = pi)) # 00000003.142
# < 左對(duì)齊 ^ 居中 > 右對(duì)齊
print('{pi:#>12.3f}'.format(pi = pi)) # #######3.142
print('{pi:#>12.3f}'.format(pi = -pi)) # ######-3.142
print('{pi:0=12.3f}'.format(pi = -pi)) # -0000003.142
center方法
# < hello >
print('<' + 'hello'.center(30) + '>') # < hello >
print('<{:^30}>'.format("hello")) # 同上
# 填充左右
print('<' + 'hello'.center(20, '*') + '>') # <*******hello********>
print('<{:*^20}>'.format("hello")) # 同上
find方法
s = 'hello world'
print(s.find('world')) # 6
# find一個(gè)不存在的
print(s.find('x')) # -1
# 出現(xiàn)多次的阁猜,返回第一次出現(xiàn)的位置
print(s.find('o')) # 4
# 從第六個(gè)位置開始找
print(s.find('o', 6)) # 7
# 指定起始位置丸逸,左閉右開
print(s.find('l', 5, 9))
join方法
myList = ['a', 'b', 'c', 'd', 'e']
s = '*'
print(s.join(myList)) # a*b*c*d*e
print(' | '.join(myList)) # aAAAbAAAcAAAdAAAe
# 生成win/Unix系統(tǒng)路徑
# C:/usr/local/nginx
# /usr/local/nginx
dirs = '', 'usr', 'local', 'nginx'
linuxPath = '/'.join(dirs)
winPath = 'C:' + '\\'.join(dirs)
print(linuxPath)
print(winPath)
#
numList = [1, 2, 3, 4, 5]
# 拋出異常
# print('a'.join(numList))
'''
Traceback (most recent call last):
File "H:\PythonWorkSpace\first-python\src\First.py", line 19, in <module>
print('a'.join(numList))
TypeError: sequence item 0: expected str instance, int found
'''
split方法
s1 = 'a b c d e f'
print(s1.split()) # ['a', 'b', 'c', 'd', 'e', 'f']
s2 = 'a**b**c**d**e**f'
print(s2.split('**')) # ['a', 'b', 'c', 'd', 'e', 'f']
path = '/usr/local/nginx'
pathList = path.split('/')
print(pathList) # ['', 'usr', 'local', 'nginx']
winPath = 'D:' + '\\'.join(pathList)
print(winPath) # D:\usr\local\nginx
upper, lower和capwords
print('Apple'.lower())
print('Apple'.upper())
myList = ['Python', 'Ruby', 'Java', 'Kotlin']
if 'KOTLIN' in myList:
print('找到Kitlin!')
else:
print('未找到Kotlin')
for lang in myList:
if 'kotlin' == lang.lower():
print("OK")
break
from string import capwords
s = 'i not only like python, but alse like kotlin.'
print(capwords(s)) # I Not Only Like Python, But Alse Like Kotlin.
replace和strip
s = 'abcdaaefg'
print(s.replace('a', '12345')) # 12345bcd1234512345efg
print(s.replace('xxxxxxx', '12345')) # 沒有就不替換
# strip (trim)
print(' asdfasdf asdfasf '.strip())
# 可以輸入多種字符剃袍,幾個(gè)字符之間是“或”的關(guān)系
s = '*** $$* Hello * World ***$$$'
print(s.strip(' *$')) # Hello * World
translate 和 maketrans
"".translate()替換單個(gè)字符串
# translate 替換單個(gè)字符
s = "I'm not only like Python, but also like Kotlin."
# 把“a”替換成"*"黄刚,把“k”替換成“$”
table = s.maketrans('ak', '*$') # {97: 42, 107: 36} ASCII : 97-a ; 42-* ; 107-k ; 36-$
print(s.translate(table)) # I'm not only li$e Python, but *lso li$e Kotlin.
table1 = s.maketrans('ak', '*$', 'P te') # {97: 42, 107: 36, 80: None, 32: None, 116: None, 101: None}
print(s.translate(table1)) #
練習(xí)1:統(tǒng)計(jì)字符串出現(xiàn)的次數(shù)
s = input("請(qǐng)輸入一個(gè)字符串:")
while True:
subStr = input('請(qǐng)輸入要統(tǒng)計(jì)的字符串:')
if subStr == 'exit()':
break
i = 0
count = 0
while i < len(s):
index = s.find(subStr, i)
if index > -1:
count += 1
i = index + len(subStr)
else:
break;
print('"{}"在字符串"{}"中出現(xiàn)了{(lán)}次。'.format(subStr, s, count))
練習(xí)2:生成一個(gè)正三角形
方法一:
n = int(input("要生成多少行:"))
# 底邊寬度: 2n-1
for i in range(1, n + 1):
print("{}".format((2 * i - 1) * '*').center(2 * n-1))
方法二:
n = int(input("要生成多少行: "))
for i in range(1, n + 1):
if i == n:
print('{}{:*<{char}}'.format('', '', char=(2 * i - 1)))
else:
print('{:{blank}}{:*<{char}}'.format('', '', blank=(n-i), char=(2 * i - 1)))