python基础:字符串内置函数

str.find()  检测字符串是否包含指定字符,并返回开始的索引值,否则返回-1

a = 'hello world!'
# find:检测字符串是否包含指定字符,并返回开始的索引值,否则返回-1
print(a.find('ol'))
# output: -1

str.index()  检测字符串是否包含指定字符,并返回开始的索引,否则提示错误

# index:检测字符串是否包含指定字符,并返回开始的索引,否则提示错误
print(a.index('ol'))
# 出错

str.count()  计算出现次数

# count:返回指定字符串在a中出现的次数
print(a.count('l'))
# output: 1
print(a.count('l', 5, len(a))) # 5到结尾,lo出现的次数
# output: 1

str.replace()  替换

# replace:将a中的str1替换成str2,如果指定count,则不超过count次
print(a.replace('l', 'L'))
# output: heLLo worLd!
print(a.replace('l', 'L', 1))
# output: heLlo world!

str.lower()   全转换为小写

# lower:将字符串转换为小写
print('HELLO woRLd!'.lower())
# output: hello world!

str.upper()   全转换为大写

# upper:将字符串转换为大写
print('Hello woRLd!'.upper())
# output: HELLO WORLD!

str.swapcase()  字符串的大小写字母互转

# swapcase:将字符串转换为大写
print('Hello woRLd!'.swapcase())
# output: hELLO WOrlD!

 str.ljust()       str.rjust()    补充并左/右对齐

# ljust:返回一个原始字符串左对齐,并使用指定字符填充至长度width的新字符串,不给定字符串默认空格
# rjust:返回一个原始字符串右对齐,并使用指定字符填充至长度width的新字符串,不给定字符串默认空格
a = 'hello'
print(a.ljust(10, '*'))
# output:hello*****
print(a.rjust(10, '*'))
# output:*****hello

 str.center()  补充并居中

# center:返回一个原字符串居中,并使用空格填充至长度width的新字符串
print(a.center(10,'*'))
# output:**hello***
a = 'hello world!'

str.split()   分割

# split: 分割字符串, 分割成num+1个字符串
print(a.split(' ', 1))
# output:['hello', 'world!']
print(a.split(' ', 0))
# output:['hello world!']

str.capitalize() 字符串首字母大写

# capitalize:字符串首字母大写
print(a.capitalize())
# output:Hello world!

 str.title()  字符串中每个单词首字母大写

# title:字符串中每个单词的首字母大写
print(a.title())
# output:Hello World!

 str.startswith()  检查字符串是否为指定字符串开头

# startswith:检查字符串是否是obj开头,是返回True,否返回False
str = "this is string example....wow!!!";
print(str.startswith( 'this' ))
print(str.startswith( 'is', 2, 4 ))
print(str.startswith( 'this', 2, 4 ))
# output:
# True
# Ture
# False

 str.endswith()  检查字符串是否为指定字符串结尾

# endswith:检查字符串是否以obj结尾,是返回True,否返回False
print(a.endswith('!'))
# output:True

猜你喜欢

转载自blog.csdn.net/qq_26271435/article/details/89519589