目录
2、upper()方法,用于将字符串全部小写字母转成大写字母
3、lower()方法,用于将字符串全部大写字母转成小写字母
4、isupper()与islower(),分别用于判断字符串内容是不是全大写,或全小写,是返回True,不是则返回False
5、count(),判断字符串中有多少个某个字符,返回具体数字。
7、index()查找字符串中的某个元素,找到第一个后返回其索引值与find不同的是,找不到时会报错
8、find() 查找字符串中的某个元素,找到第一个后返回其索引值rfind() 查找元素,但是与find不同的是,它会返回这个字符串中某个字符最后一次出现的索引
9、ljust() 文本居左,右侧填充至最大长度(括号输入的第一个参数,第二个参数为填充字符)
字符串基础
1、字符串的创建
字符串可以使用单引号('
)、双引号("
)或三引号('''
或 """
)来创建。
s1 = 'Hello, python!'
s2 = "Python is good!"
s3 = '''This is a
Code blocks'''
print(s1,s2,s3)
2、字符串的拼接
字符串可以使用 +
运算符进行拼接
s1 = "Hello"
s2 = "world"
print(s1 + " " + s2) # 输出:Hello world
3、字符串的重复
字符串可以使用 *
运算符进行重复
s = "哈哈哈"
print(s * 3) # 输出:哈哈哈哈哈哈哈哈哈
字符串的常用方法
1、len()
函数,用于获取字符串的长度
s = "Hello"
print(len(s)) # 输出:5
2、upper()方法,用于将字符串全部小写字母转成大写字母
print('abc'.upper()) # 输出ABC
3、lower()方法,用于将字符串全部大写字母转成小写字母
print('ABC'.lower()) # 输出abc
4、isupper()与islower(),分别用于判断字符串内容是不是全大写,或全小写,是返回True,不是则返回False
print('abc'.upper()) # ABC
print('ABC'.lower()) # abc
print('abc'.isupper()) # False
print('ABC'.isupper()) # True
print('ABC'.islower()) # False
print('abc'.islower()) # True
5、count(),判断字符串中有多少个某个字符,返回具体数字。
print("hello world".count('o')) # 2
6、capitalize(),将字符串的首字母大写
print("hello world".upper()) # Hello world
endswith() 判断以什么结尾
startswith() 判断以什么开头
print("hello world".endswith("D")) # False
print("hello world".startswith("h")) # True
7、index()查找字符串中的某个元素,找到第一个后返回其索引值与find不同的是,找不到时会报错
print("hello world".index("l")) # 2
print("hello world".index("x")) # 报错 没找到
8、find() 查找字符串中的某个元素,找到第一个后返回其索引值
rfind() 查找元素,但是与find不同的是,它会返回这个字符串中某个字符最后一次出现的索引
print("hello world".rfind("h")) # 输出 0
print("hello world".rfind("e")) # 输出 1
print("hello world".rfind("l")) # 输出 9
9、ljust() 文本居左,右侧填充至最大长度(括号输入的第一个参数,第二个参数为填充字符)
center() 文本居中,两侧填充至最大长度同上
rjust() 文本居右,左侧填充至最大长度同
print("hello world".ljust(20,"*")) # hello world*********
print("hello world".center(20,"*")) # ****hello world*****
print("hello world".rjust(20,"-")) # ---------hello world
10、zfill()只有一个参数,输入最大长度,填充字符为0
print("hello world".zfill(20)) # 000000000hello world
11、isalpha() 判断是不是字母
isdigit() 判断是不是数字
isascii() 检查字符串中的所有字符是否都是 ASCII 字符
print("h".isalpha()) # True
print("9".isdigit()) # True
print("hello".isascii()) # True
istitle() 检查字符串是否全部由标题单词组成,即每个单词的首字母大写,其余字母小写
isalnum() 检查字符串是否只包含字母(a-z,A-Z)和数字(0-9)
isspace() 检查字符串是否只包含空白字符。空白字符包括空格、制表符(\t)、换行符(\n)等
print("Hello World".istitle()) # True
print("he".istitle()) # False
print("hello world".isalnum()) # False hello与world中间有空格
print(" ".isspace()) # True 全空格
isdecimal() 检查字符串中的所有字符是否都是十进制数字
print('121.0'.isdecimal()) # False
print('121'.isdecimal()) # True