python字符串的处理

来源:互联网 发布:巨鹿之战 知乎 编辑:程序博客网 时间:2024/05/29 03:54
字符串:
通过索引访问字符串,几乎所有的通过索引来访问的情况,索引用下标表示,[]
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)

0 0
原创粉丝点击