您的位置:首页 > 编程语言 > Python开发

字符串常用操作方法总结

2016-09-03 15:41 141 查看
# -*- coding:utf-8 -*-
'''字符串常用操作方法总结,部分内容整理自网上'''
test_str='The Zen of Python, by Tim Peters'

'''一些简单实用的判断函数:
isalnum() #是否全是字母和数字,并至少有一个字符
isalpha() #是否全是字母,并至少有一个字符
isdigit() #是否全是数字,并至少有一个字符
isspace() #是否全是空白字符,并至少有一个字符
islower() #S中的字母是否全是小写
isupper() #S中的字母是否便是大写
istitle() #S是否是首字母大写的
startwith(prefix[,start[,end]]) #是否以prefix开头
endwith(suffix[,start[,end]]) #以suffix结尾
'''
print 'so what?!'.isalnum()#False
print 'anha1230'.isalnum()#True

print('#' * 40)

'''find 在一个较为长的字符串中查找子串,并返回子串所在位置的最左端索引,若没有则返回-1'''
print test_str.find('hello')# 没有 返回-1
print test_str.find('The')#子串所在位置的最左端索引
print test_str.find('Python')#子串所在位置的最左端索引
print('#' * 40)
'''此方法还接受可选择的起始点和结束点,注意是[起始,结束)区间'''
print test_str.find('The',1)# 没有 返回-1
print  test_str.find('The',0,2)# 没有 返回-1
print  test_str.find('The',0,3)# 没有 返回-1

print('#' * 40)

'''in 若只是想知道子串是否(bool)存在于较长的字符串 ,可以用 in'''
if 'Zen' in test_str:
print 'Zen is found in test_str!'

print('#' * 40)

'''join 连接字符串'''
sep='+'
alist=['1','2','3','4','5']#注意这里的list的元素必须是str类型的才可以使用sep来join他们,若是int型的则不行
print sep.join(alist)
print test_str.split()#默认参数是空格, ['The', 'Zen', 'of', 'Python,', 'by', 'Tim', 'Peters']

print('#' * 40)

'''split join的逆方法,拆分字符串'''
print '1+2+3+4+5'.split('+')

print('#' * 40)

'''replace 替换'''
print test_str.replace('Zen','Hen')

print('#' * 40)

'''strip 去除str两端的空格,不包括中间'''
print 'hello world!'.strip()#hello world!
print '    hello world!    '.strip()#hello world!
'''也可以指定去除两端的字符'''
print '****!!!!!hello ! world!!!!!*****'.strip('!*')#hello ! world

print('#' * 40)
'''capitalize 将字符串首字符转换为大写'''
print 'how are you!'.capitalize()#How are you!

print('#' * 40)

'''capwords 将字符串的每个字母的第一个字符转换为大写
其原理是 用split()函数分开,然后用capitalize()把首字母变成大写,最后用join()合并到一起 '''
from string import capwords
print capwords('how are you!')#How Are You!

print('#' * 40)

'''upper/lower 分别将字符串的所有字母转换为大写/小写'''
print 'how are you!'.upper()#HOW ARE YOU!
print 'HOW ARE YOU!'.lower()#how are you!

print('#' * 40)

'''swapcase 转换大小写'''
print test_str.swapcase()#tHE zEN OF pYTHON, BY tIM pETERS
print test_str.swapcase()#The Zen of Python, by Tim Peters

print('#' * 40)

'''translate 与replace一样 但优点是可以同时进行多个替换(结合maketrans函数返回的转换表),replace则只能处理单个字符串'''
from string import  maketrans
table = maketrans('Hen','Zen')#定义转换表,指定用第二个参数代替第二个参数的对应关系,maketrans接受两个等长的字符串,
print test_str.translate(table)#The Zen of Python, by Tim Peters
print test_str.translate(table,' ')#还可以在第二个参数 指定要删除的字符(s)  #TheZenofPython,byTimPeters

print('#' * 40)

'''format 如下,本段部分内容转载自http://www.cnblogs.com/hongten/archive/2013/07/27/hongten_python_format.html'''

#使用'{}'占位符
print('I\'m {},{}'.format('Hongten','Welcome to my space!'))

print('#' * 40)

#也可以使用'{0}','{1}'形式的占位符
print('{0},I\'m {1},my E-mail is {2}'.format('Hello','Hongten','hongtenzone@foxmail.com'))
#可以改变占位符的位置
print('{1},I\'m {0},my E-mail is {2}'.format('Hongten','Hello','hongtenzone@foxmail.com'))
#从这里也可以知道使用%格式字符串,要求变量有严格的次序,而.format()方法允许任意排列和重复使用
print('#' * 40)

#使用'{name}'形式的占位符
print('Hi,{name},{message}'.format(name = 'Tom',message = 'How old are you?'))

print('#' * 40)

#混合使用'{0}','{name}'形式
print('{0},I\'m {1},{message}'.format('Hello','Hongten',message = 'This is a test message!'))

print('#' * 40)

#进制与精度转换,b、d、o、x分别是二进制、十进制、八进制、十六进制
print("{0:d} - {0:x} - {0:o} - {0:b} ".format(21))#21 - 15 - 25 - 10101
#{0:d}中 0代表的是第0个变量,冒号后面就是要格式化的格式
print '{0:.2f}'.format(321.33345)#321.33
#也可写成  print '{:.2f}'.format(321.33345)  #只有一个参数时可以不用标记是第几个变量
print('#' * 40)

#对齐与填充,^、<、>分别是居中、左对齐、右对齐,后面带宽度
#:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
print '{:^5}'.format('123')#' 123 '
print '{:>5}'.format('123')#'  123'
print '{:$>5}'.format('123')#'$$123'

'''小技巧: 翻转字符串'''
print test_str[::-1]#sreteP miT yb ,nohtyP fo neZ ehT

print('#' * 40)

'''小技巧: 千位分隔符'''
print '{:,}'.format(1234567890)#1,234,567,890

''' 更加详细的请看这里: python字符串操作和string模块代码分析 ' target='_blank'>http://blog.chinaunix.net/uid-25992400-id-3283846.html'''[/code] 
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 编程 语言