python字符串

name = "my name is\t cecelia"

#第一个单词首字母大写
print(name.capitalize())
My name is cecelia

print(name.center(50,'-'))
---------------my name is cecelia----------------

print(name.count('a',0,))
2

#判断是否以。。。结尾
print(name.endswith('lia'))
True

#将字符串中的/t扩展成n个空格

print(name.expandtabs(20))
my name is           cecelia

#查找第一个子串的位置
print(name.find('name',0,20))
3

#找到后进行切片操作
print(name[name.find('name',0,20):9])
name i
print(name.index('am',1,10))
4

name1 = "his name is {name} and he is {age}"
print(name1.format(name='Liming',age=18))
his name is Liming and he is 18

print(name1.format_map({'name':'Liming','age':18}))
his name is Liming and he is 18


#判断是否是阿拉伯数字和英文字母
print(name.isalnum()) #有特殊字符
print('ab'.isalnum())
False
True

#纯英文字符
print('abd'.isalpha())
print('14432'.isdigit())
True
True
#是否是合法的标识符(变量名)
print('_as'.isidentifier())
print('sdf'.isspace())
True
False
#是否每个单词首字母都大写
print('My Name Is'.istitle())
#是否全部字符都是大写字母
print('My Name Is'.isupper())

True
False

#连接作用(很重要).join前的字符用于连接时的间隔
print('+'.join(['1','2','3']))
print('v'.join(['a','b','c']))

1+2+3
avbvc

#共n个字符,不够的话右边用给出的符号补上,区别center
print(name.ljust(50,'-'))
#共n个字符,不够的话左边用给出的符号补上,区别center
print(name.rjust(50,'-'))

my name is cecelia-------------------------------
-------------------------------my name is cecelia


#大小写转换
print('My name is '.lower())
print(name.upper())

my name is
MY NAME IS CECELIA


#去掉左边或右边或左右两边的空格与回车
print('\nAlex'.lstrip())
print('Alex\n')
print('Alex\n'.rstrip())
print(' Alex\n'.strip()) #一般用这个
print('---')

#对应替换,产生随机密码
p=str.maketrans('abcdef','123456')
print('alex'.translate(p))
1l5x

print(name.replace('e','N',2))
my namN is cNcelia

#找到符合的字符的最右侧的索引号
print(name.rfind('lia',1,20))
print(name.rindex('a',1,20))

16
18


#拆分
print(name.split(' '))
print('1+2+3+4'.split('+'))

['my', 'name', 'is\t', 'cecelia']
['1', '2', '3', '4']


print(name.startswith('na'))
False

#大小写转换
print('LOS angle'.swapcase())
los ANGLE

#将每个单词的首字母都转成大写字母
print(name.title())
My Name Is Cecelia

#用0填充不够的字符
print(name.zfill(30))
00000000000my name is cecelia
posted @ 2018-01-19 11:12  cecelia  阅读(160)  评论(0编辑  收藏  举报