python字符串的处理

字符串:
通过索引访问字符串,几乎所有的通过索引来访问的情况,索引用下标表示,[]
a="hello world"
print a[0]
print a[-1]


--通过python的for range 来处理
b="  123456789 "
a=b.strip()
total=0
for i in a:
total+=int(i)
print total


--通过字符串的下标来处理
b="  123456789 "
a=b.strip()
total=0
for i in range(len(a)):
total+=int(a[i])
print total


字符串的切片,靠的就是字符串的索引
a="elena cathrine"
first_name=a[0:4]
print first_name+"\n"
last_name=a[6:-1]
print last_name+"\n"


打印文件的后缀
def get_ext(s):
t=s.rfind('.')
ext=s[t+1:]
return ext

print get_ext("my_notebook.html")+"\n"



dir('')可以查看所有标准字符串函数
s.find(t)
s.rfind(t)
s.index(t)
s.rindex(t)


大小写字符串
s.capitalize()
s.lower()
s.upper()
s.title()将字符串修改成驼峰结构


填充字符串
s="hello"
print s.center(10,'M')
print s.rjust(10,'M')
print s.ljust(10,'M')


除掉空格的函数
s='   hello world   '
print s.strip()


s='hello world'
t=s.center(20,'M') 追加
print t
print t.strip('M') 剥离




字符串拆分函数,split 返回的是一个列表
name='elena cathrine wulka'
s=name.split(' ')
for i in s:
 print i


字符串替换函数
s='hello world'
print s.replace('hello','world')




正则表达式的使用:
python的正则表达式,只能返回真或者假
import re
s='i am quit'
m=re.match(r'(.*)(done|quit)$',s)
print m.string
print m.group(2)
print m.group(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值