小白python爬蟲之路——對字符串的處理
對字符串的處理分類:分段,連接,剔除,提取,綜合
連接:+,*
+(加法)的使用
a=‘i‘
b=‘ love‘
c=‘ you‘
print(a+b+c)
#return i love you
*(乘法)的使用
a=‘word‘
print(a*3)
#result wodwordword
分段:split()
split():將字符串按標誌(默認為空格)分成列表格式
a=‘www.baidu.com‘
print(a.split(‘.‘))
#return [‘www‘,‘baidu‘,‘com‘]
剔除:strip(),
strip():剔除兩側字符,默認空格,自定義為!結尾。
#默認
a=‘ python is cool ‘
print(a.strip())
#return ‘python is cool‘
#自定義
a=‘*********python **is** cool***********‘
print(a.strip(‘*!‘))
#return ‘python **is** cool‘
提取:切片和索引
切片和索引
索引:正值和負值
a=‘123456789‘
print(a[0])
#return 1
print(a[-1])
#return 9
切片:包頭不包尾(將數字看成角標)
a=‘123456789‘
print(a[0:1])
#return 1
print(a[0:3])
#return 123
綜合:替換, 字符串格式化符
替換:replace(), 原值=》替換值
如果有多個原值效果未知
以值查詢或位置查詢為索引替換
替換is為are
a=‘‘there is apples‘‘
b=a.replace(‘is‘,‘are‘)
print(b)
#return ‘there are apples‘
將電話號碼中間四位屏蔽
def change_number(number):
hiding_number=number.replace(number[3:7],‘*‘*4)
print(hiding_number)
change_number(‘13813986643‘)
#return 138****6643
format(): 單詞用replace(),長句用format()
#字符串使用
a=‘{} is my love‘.format(‘python‘)
print(a)
#return ‘python is my love‘
#url使用
content=input(‘輸入搜索內容?‘)
url_path=‘https://www.abc.com/{}‘.format(content)
print(url_path)
#url_path=www.abc.com.content
小白python爬蟲之路——對字符串的處理