2021-03-24 python数据处理系统学习(四)字符串处理

2021-03-24 python数据处理系统学习(四)字符串处理

1、字符串运算符

   ...: print('hello\nworld')#\n为换行符
   ...: print('hello\tworld')#\t为制表符
hello world
hello
world
hello	world

In [2]: print(r'hello\tworld')#r防止转义
hello\tworld

print('hello\bworld')#\b退格
print('hello\b\bworld')#\b退格
hellworld
helworld

2、字符串格式化符号

print('我今年%s岁'%20)#s为格式化字符串
print('我今年%d岁'%20.5)#d为格式化整数
print('我今年%s岁'%20.5)#s为格式化字符串
print('我今年%.2f岁'%20.545)#格式化浮点数字,可指定小数点后的精度,.2f:保留两位小数
print('我今年%.2e岁'%20.545234)#用科学计数法格式化浮点数字,可指定小数点后的精度,.2f:保留两位小数
我今年20岁
我今年20岁
我今年20.5岁
我今年20.55岁
我今年2.05e+01岁

print('我国gdp增速为%.2f%%'%12.345)#%%输出一个%
我国gdp增速为12.35%

#两种引用的方式
print('我今年%s岁,我读%s'%(22,'大四'))
print('我今年{:.2f}岁,我读{}'.format(22,'大四'))
我今年22岁,我读大四
我今年22.00岁,我读大四

3、一些相关函数

①split函数对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
②find函数

data='123456789'
print(data.find('4'))
print(data.find('10'))
3
-1

返回-1表示没有找到
③index

data='123456789'
print(data.index('4'))
print(data.index('10'))
3
Traceback (most recent call last):

  File "<ipython-input-18-827880bf0375>", line 3, in <module>
    print(data.index('10'))

ValueError: substring not found

如果是用index检索不存在的字符,则会直接报错。
④lower、upper、capitalize

s='This is China'
print(s.lower())#全部输出为小写
print(s.upper())#全部输出为大写
this is china
THIS IS CHINA

s.capitalize()#首字母大写
Out[21]: 'This is china'

⑤join
以’ '里的内容为分隔符插入字符串,形成新的字符串

"!".join(s)
Out[22]: 'T!h!i!s! !i!s! !C!h!i!n!a'

⑥strip
去除空格

s=' This is China '
print(s.lstrip())#去除最左的空格
print(s.rstrip())#去除最右的空格
This is China 
 This is China

⑦isdigit()

s.isdigit()#判断字符串是否全部由数字构成
Out[24]: False

即便存在空格,输出的也是false
⑧endswith判断结尾

s.endswith('China')
Out[26]: False

s.endswith('China ')
Out[27]: True

⑨isalnum

s.isalnum()#如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
Out[28]: False

⑨count

s.count('s')#统计s在字符串中出现的次数
Out[32]: 2
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值