Python中常用字符串方法总结

# isalnum()方法检查字符串是否只包含字母和数字。 == is alphanumeric的缩写
s = "Hello123"
print(s.isalnum())  # 输出: True 

# isalpha()方法检查字符串是否只包含字母。
s = "Hello"
print(s.isalpha())  # 输出: True

# isdigit()方法检查字符串是否只包含数字
s = "123"
print(s.isdigit())  # 输出: True

# islower()方法检查字符串是否全部为小写
s = "hello"
print(s.islower())  # 输出: True

# isupper()方法检查字符串是否全部为大写
s = "HELLO"
print(s.isupper())  # 输出: True

# lower()方法将字符串中的所有字符转换为小写
s = "Hello"
print(s.lower())  # 输出: hello

# upper()方法将字符串中的所有字符转换为大写
s = "hello"
print(s.upper())  # 输出: HELLO

# capitalize()方法将字符串的第一个字符转换为大写,其余字符转换为小写。
s = "hEllo wOrld"
print(s.capitalize())  # 输出: Hello world

# title()方法将字符串中每个单词的第一个字符转换为大写,其余字符转换为小写。
s = "hello worLd"
print(s.title())  # 输出: Hello World

# strip()方法去除字符串两端的空白字符
s = "  hello  "
print(s.strip())  # 输出: hello

# lstrip()方法去除字符串左侧的空白字符
s = "  hello"
print(s.lstrip())  # 输出: hello

# rstrip()方法去除字符串右侧的空白字符
s = "hello  "
print(s.rstrip())  # 输出: hello

# startswith()方法检查字符串是否以指定的子字符串开头
s = "Hello, world!"
print(s.startswith("Hello"))  # 输出: True

# endswith()方法检查字符串是否以指定的子字符串结尾
s = "Hello, world!"
print(s.endswith("world!"))  # 输出: True

# find()方法返回指定子字符串在字符串中的索引,如果没找到,就返回-1
s = "Hello, world!"
print(s.find("world"))  # 输出: 7  == find函数可以接收第二个参数和第三个参数,用于指定查找的开始索引和结束索引

# index()方法返回指定子字符串在字符串中的索引
s = "Hello, world!"
print(s.index("world"))  # 输出: 7  == index函数可以接收第二个参数和第三个参数,用于指定查找的开始索引和结束索引

# 总结来说,index()方法和find()方法都用于在字符串中查找子字符串的位置。它们的主要区别在于:
    # index()方法在未找到子字符串时会抛出异常,而find()方法会返回-1。
    # 在大多数情况下,find()方法更为灵活,因为它不会引发异常,而是返回一个明确的值(-1)来表示未找到。
    # find()方法通常在性能上优于index()方法,特别是在处理可能未找到子字符串的情况时。

# replace()方法将字符串中的指定子字符串替换为另一个字符串
s = "Hello, world!"
print(s.replace("world", "Python"))  # 输出: Hello, Python!

# split()方法将字符串按照指定的分隔符分割成多个子字符串,返回一个列表。
s = "Hello, world!"
print(s.split())  # 输出: ['Hello,', 'world!']

# join()方法将一个可迭代对象(如列表)中的元素使用指定的字符串连接起来,返回一个新的字符串。
s = ["Hello", "world!"]
print(' '.join(s))  # 输出: Hello world!  == 带空格
print(''.join(s))  # 输出: Helloworld!  === 不带空格
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值