Python从零开始 day6

字符串的内置方法:

a='123'
b='abc'

print(a[1:]) #23
print('a' in b) #True

c='-----'.join([a,b])
#print(c) #123abc

print(c) #123-----abc


st = 'hello world'

print(st.count('l')) #统计某个元素的个数

print(st.capitalize()) #首字母大写

print(st.center(20,'-')) #----hello world----- 居中分布
print(st.ljust(20,'-')) #hello world--------- 左居中
print(st.rjust(20,'-')) #---------hello world 右居中

print(st.endswith('d')) #判断是否以什么结尾 正确返回True 错误返回False
print(st.startswith('h')) #判断是否以什么开头 正确返回True 错误返回False


st1 = 'hel\tlo world'
print(st1.expandtabs(tabsize=10)) #在想要某个位置加10个空格,用\t来分隔 hel lo world

print(st1.find('o')) #查找第一个元素,并将索引值返回 5 如果不存在则会返回-1
print(st1.index('o')) #查找第一个元素,并将索引值返回 5,如果查找的元素不存在则会出现错误



st2 = 'hello world {name} is {adj}'
print(st2.format(name='python',adj='good')) #hello world python is good 用于格式化输出,通过赋值来改变变量的值
print(st2.format_map({'name':'python','adj':'good'})) #hello world python is good,通过字典键值对来改变变量

st3 = 'helloworld123'
print(st3.isalnum()) #判断字符串是否是由字母和数字组成,不支持特殊字符(空格),支持中文

print('1256'.isdecimal()) #判断是否是十进制

print('125698'.isdigit()) #判断是否是整数,只能是整数
print('125698'.isnumeric()) #判断是否是整数,只能是整数
print('abc'.isidentifier()) #检查变量是否是非法字符

print('abc'.islower()) #判断是否是全部小写,存在一个大写都会返回False
print('ABC'.isupper()) #判断是否是全部大写,存在一个小写都会返回False

print('ABC'.lower()) #将大写变小写
print('abc'.upper()) #将小写变大写
print('My Book'.swapcase()) #将大写变小写,小写变大写


print(' '.isspace()) #判断是否是空格
print('My Book'.istitle()) #判断标题是否合法 即首字母大写


st3 = 'name'
st4 = 'is'
st5 = 'fishy'
#name is fishy 将几个字符串拼接起来 引号里面可以是特殊字符,用于连接字符串
print(' '.join([st3,st4,st5]))


print(' book , good\n'.strip()) #book , good, 去除左右两边的空格和换行
print(' book , good\n'.lstrip()) #book , good, 去除左边的空格和换行
print(' book , good\n'.rstrip()) # book , good,去除右边的空格和换行

'''this is my grilfriend 替换存在三个参数,一个需要替换的,另一个被替换的,
最后是替换的频次(替换几个或几次) 也可替换内容的一部分'''
print('this is my friend'.replace('friend','grilfriend'))
print('this is my friend'.replace('end','gril')) #this is my frigril
print('this is my friend end end'.replace('end','gril',2)) #this is my frigril gril end


print('this is my friend end end'.rfind('e')) #22 从左往右索引最右边第一个e

#分割成列表形式 ['this', 'is', 'my', 'friend', 'end', 'end'],以左为准
print('this is my friend end end'.split(' '))
print('this is my friend end end'.split('i')) #['th', 's ', 's my fr', 'end end end']

#通过join方法可以将列表组合成字符串
print(' '.join(['this', 'is', 'my', 'friend', 'end', 'end']))
print('i'.join(['th', 's ', 's my fr', 'end end end']))

#以i为分界 分为几组(取决于rsplit的参数为几,再加一),以靠右为基准
print('this is my friend end end'.rsplit('i',1)) #['this is my fr', 'end end end']


print('my book'.title()) #My Book 将首字母大写

猜你喜欢

转载自www.cnblogs.com/yubang178/p/10182573.html
今日推荐