【Python入门与进阶】Python中字符串常用方法

在Python中,字符串是不可变的序列类型,包含许多内置的方法来操作和处理字符串。以下是一些常用的字符串方法:

1. str.upper()str.lower()

将字符串转换为大写或小写。

s = "Hello, World!"
print(s.upper())  # 输出: HELLO, WORLD!
print(s.lower())  # 输出: hello, world!

2. str.strip(), str.lstrip(), str.rstrip()

移除字符串两端(或指定方向)的空白字符或指定字符。

s = "  Hello, World!  "
print(s.strip())   # 输出: "Hello, World!"
print(s.lstrip())  # 输出: "Hello, World!  "
print(s.rstrip())  # 输出: "  Hello, World!"

3. str.split()str.join()

分割字符串为列表或将列表中的字符串合并为一个字符串。

s = "Hello, World!"
print(s.split())           # 输出: ['Hello,', 'World!']
print(s.split(','))        # 输出: ['Hello', ' World!']

words = ["Hello", "World"]
print(" ".join(words))     # 输出: "Hello World"

4. str.replace()

替换字符串中的指定子字符串。

s = "Hello, World!"
print(s.replace("World", "Python"))  # 输出: "Hello, Python!"

5. str.find()str.index()

查找子字符串在字符串中的位置。find 方法在找不到子字符串时返回 -1,index 方法则会引发 ValueError 异常。

s = "Hello, World!"
print(s.find("World"))  # 输出: 7
print(s.index("World")) # 输出: 7
#print(s.find("Python")) # 输出: -1
#print(s.index("Python")) # ValueError: substring not found

6. str.startswith()str.endswith()

检查字符串是否以指定的前缀或后缀开头或结尾。

s = "Hello, World!"
print(s.startswith("Hello"))  # 输出: True
print(s.endswith("World!"))   # 输出: True

7. str.capitalize(), str.title(), str.swapcase()

修改字符串的大小写。

s = "hello, world!"
print(s.capitalize())  # 输出: "Hello, world!"
print(s.title())       # 输出: "Hello, World!"
print(s.swapcase())    # 输出: "HELLO, WORLD!"

8. str.isalpha(), str.isdigit(), str.isalnum(), str.isspace()

检查字符串是否全为字母、数字、字母和数字的组合或空白字符。

s1 = "Hello"
s2 = "1234"
s3 = "Hello123"
s4 = "   "

print(s1.isalpha())   # 输出: True
print(s2.isdigit())   # 输出: True
print(s3.isalnum())   # 输出: True
print(s4.isspace())   # 输出: True

9. str.count()

计算子字符串在字符串中出现的次数。

s = "Hello, World! Hello!"
print(s.count("Hello"))  # 输出: 2

10. str.format()

字符串格式化。

name = "Alice"
age = 30
s = "My name is {} and I am {} years old.".format(name, age)
print(s)  # 输出: My name is Alice and I am 30 years old.

11. str.zfill()

在字符串前填充零,以达到指定的长度。

s = "42"
print(s.zfill(5))  # 输出: "00042"

12. str.partition()str.rpartition()

将字符串分割成三部分:分隔符前的部分、分隔符本身、分隔符后的部分。

s = "Hello, World!"
print(s.partition(","))  # 输出: ('Hello', ',', ' World!')
print(s.rpartition(",")) # 输出: ('Hello', ',', ' World!')
  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值