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

#_*_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())









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值