Python之字符串

字符串的定义

在这里插入图片描述
在这里插入图片描述

字符串的特性
#索引: 0,1,2,3,4 索引值默认从0开始
s = 'hello'

print(s[1])
print(s[0])

在这里插入图片描述

#切片
print(s[0:3])   #切片的规则: s[start:end:step] 从start开始,到end-1结束,步长:step

print(s[0:4:2])

#显示所有字符
print(s[:])

#显示前3个字符
print(s[:3])

#字符串逆序输出
print(s[::-1])

#除了第一个字符以外,其他全部输出
print(s[1:])
#重复
print( s * 10)
#连接
print('hello' + ' ' + 'world')
#成员操作符
print('h' in s)
print('q' in s)

小练习:回文数判断
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

字符串判断
#判断字符串里面每个元素是否为某种类型
# print('123'.isdigit())
# print('123abc'.isdigit())

#title:首字母大写,其余字母小写
# print('Hello'.istitle())
# print('HeLlo'.istitle())
#
# print('hello'.upper())
# print('hello'.isupper())
# print('hElLo'.lower())
# print('hElLo'.islower())

# print('hello123'.isalnum())

# print('123'.isalpha())
# print('abc'.isalpha())

print(isinstance(1,int))
print(isinstance('a',str))
print(isinstance(1,str))
字符串去掉开头和结尾
# In [8]: s = '    hello   '
#
# In [9]: s.strip()
# Out[9]: 'hello'
#
# In [10]:
#
# In [10]: s.lstrip()
# Out[10]: 'hello   '
#
# In [11]: s.rstrip()
# Out[11]: '    hello'
#
# In [12]: s = '    \nhello   '
#
# In [13]: s.strip()
# Out[13]: 'hello'
#
# In [14]: s = '    \thello   '
#
# In [15]: s.strip()
# Out[15]: 'hello'
#
# In [16]: s = 'helloh'
#
# In [17]: s.strip('h')
# Out[17]: 'ello'
#
# In [18]: s.lstrip('he')
# Out[18]: 'lloh'
字符串匹配开头和结尾
# filename = 'hello.log'
# if filename.endswith('.log'):
#     print(filename)
# else:
#     print('error')

url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub'
url3 = 'http://172.25.254.250/index.html'

if url3.startswith('http://'):
    print('爬取该网页')
else:
    print('错误网页')

#####字符串的搜索和替换

s = 'hello world hello'

#find找到子串,并返回最小的索引
print(s.find('hello'))
print(s.find('world'))

#rfind找到子串,并返回最大的索引值
print(s.rfind('hello'))

#替换字符串中所有的‘hello’为‘westos’
print(s.replace('hello','westos'))

在这里插入图片描述

字符串的对齐

在这里插入图片描述
在这里插入图片描述

字符串的统计

在这里插入图片描述
在这里插入图片描述

字符串的分离和连接

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值