小白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‘)

#return138****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爬虫之路——对字符串的处理

评论关闭