码迷,mamicode.com
首页 > 编程语言 > 详细

python字符串

时间:2017-11-14 19:44:06      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:获取   找不到   width   iss   alt   整理   api   color   display   

整理一下python内置的字符串操作

# 1字母处理:
.upper()    # 全部大写
.lower()    # 全部小写
.swapcase()    # 大小写互换
.capitalize()    # 首字母大写,其余小写
.title()    # 首字母大写
技术分享
a=helLO

print(a.upper())    # 全部大写
print(a.lower())    # 全部小写
print(a.swapcase()) # 大小写互换
print(a.capitalize())   # 首字母大写,其余小写
print(a.title())    # 首字母大写
View Code
# 2格式化相关

.ljust(width)     # 获取固定长度,左对齐,右边不够用空格补齐
.rjust(width)     # 获取固定长度,右对齐,左边不够用空格补齐
.center(width)  # 获取固定长度,中间对齐,两边不够用空格补齐
.zfill(width)      # 获取固定长度,右对齐,左边不足用0补齐
技术分享
a=1 2
print(a.ljust(10))  # 获取固定长度,左对齐,右边不够用空格补齐
print(a.rjust(10))  # 获取固定长度,右对齐,左边不够用空格补齐
print(a.center(10)) # 获取固定长度,中间对齐,两边不够用空格补齐
print(a.zfill(10))  # 获取固定长度,右对齐,左边不足用0补齐


执行结果:
1 2       
       1 2
   1 2    
00000001 2
View Code

 

# 3 字符串搜索相关

.find()    # 搜索指定字符串,没有返回-1
.index()    # 同上,但是找不到会报错
.rfind()    # 从右边开始查找
.count()    # 统计指定的字符串出现的次数

# 上面所有方法都可以用index代替,不同的是使用index查找不到会抛异常,而find返回-1
s=hello world
print(s.find(e))  # 搜索指定字符串,没有返回-1
print(s.find(w,1,2))  # 顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
print(s.index(w,1,2)) # 同上,但是找不到会报错
print(s.count(o)) # 统计指定的字符串出现的次数
print(s.rfind(l)) # 从右边开始查找

 

# 4字符串替换

.replace(old,new)    # 替换old为new
.replace(old,new,次数)    # 替换指定次数的old为new


s=hello world
print(s.replace(world,python))
print(s.replace(l,p,2))
print(s.replace(l,p,5))

执行结果:
hello python
heppo world
heppo worpd

 

# 5字符串去空格及去指定字符

.strip()    # 去两边空格
.lstrip()    # 去左边空格
.rstrip()    # 去右边空格

.split()    # 默认按空格分隔
.split(指定字符)    # 按指定字符分割字符串为数组


s=   h e-l lo   
print(s)
print(s.strip())
print(s.lstrip())
print(s.rstrip())
print(s.split(-))
print(s.split())

 

# 6字符串判断相关

.startswith(start)    # 是否以start开头
.endswith(end)    # 是否以end结尾
.isalnum()    # 是否全为字母或数字
.isalpha()    # 是否全字母
.isdigit()    # 是否全数字
.islower()    # 是否全小写
.isupper()    # 是否全大写
.istitle()    # 判断首字母是否为大写
.isspace()    # 判断字符是否为空格

 

python字符串

标签:获取   找不到   width   iss   alt   整理   api   color   display   

原文地址:http://www.cnblogs.com/shenbuer/p/7833953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!