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

python基础--字符串常用函数

2017-11-24 15:53 537 查看
#_*_coding:utf-8_*_
"""
字符串常用函数
"""
str1 = 'hello world'
"""
find()  检查字符串是否包含指定的字符,
没包含返回-1,
包含返回开始的索引值
"""
# 3
print(str1.find('lo'))
# -1
print(str1.find('yy'))

"""
index() 检查字符串是否包含指定的字符,
包含-返回开始的索引值
不包含-提示错误
"""
# 3
print(str1.index('lo'))
# ValueError: substring not found
# print(str1.index('yy'))

"""
count 返回str1在string中指定索引返回内[start, end]出现的次数
"""
print(str1.count('lo'))
print(str1.count('lo', 5, len(str1)))

"""
replace 将str1中的str1替换成str2,如果指定count,则不超过count次数
"""
print(str1.replace('hello', 'HELLO'))
print(str1.replace('hello', 'HELLO', 1))
print(str1.replace('l', 'L', 2))

"""
split 如果maxsplit有指定值,则仅分割maxsplit个子字符串
"""
str1 = 'hello world hello china'
# ['hello', 'world', 'hello', 'china']
print(str1.split(' '))
# ['hello', 'world hello china']
print(str1.split(' ', 2))

"""
capitalize 将字符串的首字母大写
"""
str1 = 'hello world hello china'
print(str1.capitalize())

"""
title 把字符串中每个单词的首字母大写
"""
print(str1.title())

"""
startswith 检查字符串是否以obj开头,
是 返回 Ture
否 返回 False
endswith  检查字符串是否以obj结尾
是 返回 True
否 返回 False
"""
str1 = 'hello world hello china'
print(str1.startswith('hello'))

"""
lower 将字符串转换为小写
upper 将字符串转换为大写
"""
str1 = 'hello world hello china'
print(str1.lower())
print(str1.upper())

"""
ljust 返回一个原字符串左对齐,并使用空格填充至长度width的新字符串
rjust 返回一个字符串右对齐,并使用空格填充至长度width的心字符串
center 返回一个原字符串居中,并使用空格填空至长度width的新字符串
"""
str1 = 'hello'
# hello     ,
print(str1.ljust(10))
# ,     hello
print(str1.rjust(10))
# ,  hello   ,
print(str1.center(10))

"""
lstrip 去除字符串左边空白字符
rstrip 去除字符串右边空白字符
strip 去除两边空白字符
"""
str1 = '    hello'
print(str1.lstrip())
str1 = 'hello   '
print(str1.rstrip())
str1 = '    hello   '
print(str1.strip())

"""
partition 可以将字符串以str1进行分割成三个部分,str1前, str1, str1后
"""
str1 = 'hello world hello china'
# ('hello ', 'world', ' hello china')
print(str1.partition('world'))

"""
join list中每个字符串后面插入str1,构造出一个新的字符串
"""
str1 = '_'
list=['hello', 'world', 'hello', 'china']
print(str1.join(list))

"""
isspace 如果str1中只包含空格,则返回True,否则返回False
"""
str1=' '
print(str1.isspace())

"""
isalnum 如果str1所有字符都是字母或数字则返回True,否则返回False
isdigit 如果str1只包含数字则返回True,否则返回False
isalpha 如果str1所有字符都是字母,则返回True,否则返回False
"""
str1='a123'
print(str1, str1.isalnum())
print(str1.isdigit())
print(str1.isalpha())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: