Backto Python Index
文章目录
基础语法
实用函数
查找函数: index() 与 find()
str1 = 'hello.mp4'
str1.index("mp4") # = 6
str1.index("mp3") # raise "ValueError: substring not found"
str1.find("mp4") # = 6
str1.find("mp3") # = -1
index
的作用是返回下标,一旦找不到则报错。不可能返回 -1
,因为在 Python 字符串里,index = -1
代表倒数第一个字符。而 find 的作用是查找,找到了就返回正序的index,找不到返回 -1
代表 False.
分割 split
>>> s = 'img1.jpg@@@img2.jpg@@@img3.jpg'
>>> s.split('@@@')
['img1.jpg', 'img2.jpg', 'img3.jpg']
判定函数 startswith() & endswith()
>>> s = 'hello world'
>>> s.startswith('h')
True
>>> s.endswith('!')
False
格式化 Formats
一文搞定,Using % and .format() for great good!
# 浮点数位数, 小数点也占一位
'{:06.2f}'.format(3.141592653589793) # => "003.14"
## eg: 小数转百分数
'{:.2f}%'.format(percentage*100)
# signed number # d for int, f for float
'{:+d}'.format(42) # => "+42"
# align right
'{:>10}'.format('test') # => "******test"
# align left
'{:10}'.format('test')# => "test******"
# align center(new)
'{:^11}'.format('test') # => "***test****"
# string truncate
'{:.5}'.format('xylophone') # => "xylop"
# string truncate & padding
'{:10.5}'.format('xylophone') # => "xylop*****"
# placeholder
'{first} {last}'.format(first='Hodor', last='Hodor!')
#get item or get attr
## for dict
person = {'first': 'Jean-Luc', 'last': 'Picard'}
'{p[first]} {p[last]}'.format(p=person) # => "Jean-Luc Picard"
## for list
data = [4, 8, 15, 16, 23, 42]
'{d[4]} {d[5]}'.format(d=data) # => "23 42"
## for class attr
class Plant(object):
type = 'tree'
'{p.type}'.format(p=Plant()) # => "tree"
# datetime
from datetime import datetime
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5)) # => 2001-02-03 04:05
小栗子
微信公众号文章分享链接截取有效部分
wechat_article_share_url_cut.py
origin_url = r'https://mp.weixin.qq.com/s?__biz=MzI0MTcwODI2OQ==&mid=2247484655&idx=1&sn=efe478107473be1a0b4ce3f8fc863053&chksm=e906396dde71b07bc82256832920f277147bc41f73fed7df07bfc8b1581594a2bdb74914884f&mpshare=1&scene=1&srcid=09191db3nIPuMQWUyVdSYRvj&from=singlemessage&ascene=1&devicetype=android-26&version=2607023a&nettype=WIFI&abtest_cookie=BQABAAgACgALABIAEwAFAJ2GHgAjlx4AWZkeAGKZHgBsmR4AAAA%3D&lang=zh_CN&pass_ticket=3JOiGSHpFdxde5JzQTov4cRGTaE08lkflBRI3Ii%2BG5undW0YFiyujnrEmh9g9u6Y&wx_header=r';
end_index = origin_url.find('&chksm=')
print('\n')
print(origin_url[:end_index])
print('\n')