【7.2 python中的字符串常用操作】

python中的字符串常用操作


Python中的字符串(str 类型)提供了丰富的操作方法来处理文本数据。以下是一些常用的字符串操作:

1. 字符串拼接

  • 使用加号(+)操作符可以将两个或多个字符串拼接成一个新的字符串。
s1 = "Hello, "
s2 = "world!"
s3 = s1 + s2  # 结果为 "Hello, world!"

2. 字符串重复

  • 使用乘号(*)操作符可以将字符串重复指定的次数。
s = "abc"
repeated_s = s * 3  # 结果为 "abcabcabc"

3. 字符串索引

  • 可以通过索引(索引从0开始)访问字符串中的单个字符。
s = "hello"
print(s[0])  # 输出 'h'
print(s[-1])  # 输出 'o',负索引表示从字符串末尾开始计数

4. 字符串切片

  • 切片操作允许你获取字符串的一个子串。
s = "hello world"
print(s[0:5])  # 输出 'hello',从索引0到索引5(不包括索引5)
print(s[6:])   # 输出 'world',从索引6到字符串末尾
print(s[:-6])  # 输出 'hello ',从索引0到索引-6(不包括索引-6)

5. 字符串长度

  • 使用 len() 函数可以获取字符串的长度(即包含的字符数)。
s = "hello"
print(len(s))  # 输出 5

6. 字符串查找

  • find() 方法用于查找子串在字符串中的位置(索引),如果未找到则返回 -1
  • index() 方法与 find() 类似,但如果未找到子串则会引发 ValueError
s = "hello world"
print(s.find("world"))  # 输出 6
print(s.index("python"))  # 抛出 ValueError

7. 字符串替换

  • replace() 方法用于替换字符串中的某些字符或子串。
s = "hello world"
new_s = s.replace("world", "Python")  # 结果为 "hello Python"

8. 字符串分割

  • split() 方法用于将字符串分割成子串列表,默认按空白字符(空格、换行符等)分割。
s = "apple,banana,cherry"
fruits = s.split(",")  # 结果为 ['apple', 'banana', 'cherry']

9. 字符串格式化

  • Python 提供了多种字符串格式化方法,如 % 操作符、str.format() 方法以及 f-string(Python 3.6+)。
name = "Alice"
age = 30
# 使用 % 操作符
s = "Name: %s, Age: %d" % (name, age)
# 使用 str.format()
s = "Name: {}, Age: {}".format(name, age)
# 使用 f-string
s = f"Name: {name}, Age: {age}"

10. 字符串去空格

  • strip() 方法用于去除字符串两端的空白字符(包括空格、换行符等)。
  • lstrip()rstrip() 分别用于去除字符串左端和右端的空白字符。
s = "   hello world   "
print(s.strip())  # 输出 'hello world'

11. 字符串大小写转换

  • upper() 方法将字符串中的所有小写字母转换为大写字母。
  • lower() 方法将字符串中的所有大写字母转换为小写字母。
  • capitalize() 方法将字符串的第一个字符转换为大写字母,其余字符转换为小写字母。
  • title() 方法将字符串中每个单词的首字母转换为大写字母,其余字符转换为小写字母。
s = "hello world"
print(s.upper())  # 输出 'HELLO WORLD'
print(s.lower())  # 输出 'hello world'
print(s.capitalize())  # 输出 'Hello world'
print(s.title())  # 输出 'Hello World'

这些只是Python中字符串操作的一部分,但它们是处理文本数据时最常用的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wang151038606

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值