Python学习日记-11-字符串操作

print('hello'*2)    #重复打印

print('hello world'[3:])  #通过索引打印,和切片原理相同

print('el' in 'hello')    #判断第一个字符串是否在第二个字符串里  True
print(12 in [12,55,123])  #判断列表,同上  True

#----格式化输出----
print('xiaoran is studying')
print('%s is studying' %'xiaoran')  #使输出的字符串更灵活

#----字符串拼接----
a = '123'
b = 'abc'
c = a + b   #可以,但效率比较低,占用内存,应用join方法
print(c)

e1 = ''.join([a,b])  #结果:123abc  空字符串作为两个字符串连接符,拼接字符串
print(e1)
e2 = '-----'.join([a,b])   #结果:123-----abc
print(e2)
e3 = '---'.join([a,b,c])   #结果:123---abc---123abc
print(e3)

#-----字符串的内置方法---

st = 'hello kitty'
st1 = '{name} is {age}'

print(st.count('l'))         #统计字符个数  (重要)
print(st.capitalize())       #每个单词首字母大写  结果:Hello kitty
print(st.center(50,'-'))     #两边加一个字符居中  结果:-------------------hello kitty--------------------  (重要)
print(st.endswith('ty'))     #判断是否以某字符串结束  结果:True
print(st.startswith('he'))   #判断是否以某个字符开始  结果:True  (重要)
print(st.find('t'))          #查找到第一个元素,并将索引值返回(若原字符串不存在要查找的字符,返回-1)  (重要)
print(st.index('t'))         #查找到第一个元素,并将索引值返回(若原字符串不存在要查找的字符,程序报错)  (重要)
print(st1.format(name = 'xiaoran',age = 20))          #格式化输出  (重要)
print(st1.format_map({'name':'xiaoran','age':20}))    #格式化输出
print('asd$'.isalnum())      #只含有字母,数字,汉字为True,若有其他为False
print('b0011'.isdecimal())   #若为十进制输,为True,若有其他为False
print('222'.isdigit())         #判断是否为整型数字,是为True,若有其他为False
print('22.2'.isnumeric())      #判断是否为整型数字,是为True,若有其他为False
print('33abc'.isidentifier())  #判断是否为非法字符,是为False,不是为True
print('asd'.islower())         #判断字母是否为全小写
print('asd'.isupper())         #判断字母是否为全大写
print(' a'.isspace())          #判断是否为全空格
print('Asd Ess'.istitle())     #判断是否为标题(首字母大写)
print('AnGh'.lower())          #大写字母变小写    (重要)
print('AnGh'.upper())          #小写字母变大写    (重要)
print('AnGh'.swapcase())       #大写字母变小写,小写字母变大写
print('My Name'.ljust(20,'*'))   #结果:My Name*************
print('My Name'.rjust(20,'*'))   #结果:*************My Name
print('   My Name   \n'.strip())     #清楚开始和结尾的换行符,空格    (重要)(重要)(重要)
print('My Name Name'.replace('Name','age',1))   #替换一次  结果:My age Name   (重要)
print('My Name Name'.rfind('a'))       #从左往右查找
print('My Name Name'.split(' ',1))     #空格键分割,分割一次,返回成一个列表。    join可以把列表转化为字符串  (重要)
print('My name name'.title())          #题目格式输出

猜你喜欢

转载自blog.csdn.net/wuli_xiaoran/article/details/81810049