python之字符串

创建字符串

s = "Hello, World!"

常用字符串操作

  1. 获取字符串长度
length = len(s)
print(length)  # 输出: 13
  1. 字符串拼接
s1 = "Hello"
s2 = "World"
s3 = s1 + ", " + s2 + "!"
print(s3)  # 输出: Hello, World!
  1. 重复字符串
s = "Hello"
s_repeated = s * 3
print(s_repeated)  # 输出: HelloHelloHello
  1. 字符串格式化
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)  # 输出: My name is Alice and I am 30 years old.
  1. 字符串分割
s = "Hello, World!"
parts = s.split(", ")
print(parts)  # 输出: ['Hello', 'World!']
  1. 字符串连接
words = ["Hello", "World"]
joined_string = " ".join(words)
print(joined_string)  # 输出: Hello World
  1. 字符串替换
s = "Hello, World!"
new_s = s.replace("World", "Python")
print(new_s)  # 输出: Hello, Python!
  1. 字符串查找
s = "Hello, World!"
index = s.find("World")
print(index)  # 输出: 7
  1. 字符串大小写转换
s = "Hello, World!"
print(s.upper())  # 输出: HELLO, WORLD!
print(s.lower())  # 输出: hello, world!
print(s.capitalize())  # 输出: Hello, world!
print(s.title())  # 输出: Hello, World!
  1. 去除空白字符
s = "  Hello, World!  "
print(s.strip())  # 输出: Hello, World!
print(s.lstrip())  # 输出: Hello, World!  
print(s.rstrip())  # 输出:   Hello, World!

子字符串的用法

  1. 获取子字符串
s = "Hello, World!"
sub_s = s[7:12]
print(sub_s)  # 输出: World
  1. 检查子字符串
s = "Hello, World!"
print("World" in s)  # 输出: True
print("Python" in s)  # 输出: False
  1. 子字符串计数
s = "Hello, World! Hello, Python!"
count = s.count("Hello")
print(count)  # 输出: 2
  1. 子字符串索引
s = "Hello, World!"
index = s.index("World")
print(index)  # 输出: 7

# 如果子字符串不存在,会抛出 ValueError
try:
    index = s.index("Python")
except ValueError:
    print("Substring not found")
  1. 子字符串切片
s = "Hello, World!"
sub_s = s[7:]  # 从索引 7 开始到结尾
print(sub_s)  # 输出: World!

sub_s = s[:5]  # 从开头到索引 5(不包括 5)
print(sub_s)  # 输出: Hello

sub_s = s[::2]  # 每隔一个字符取一个
print(sub_s)  # 输出: Hlo ol!

str.find()与str.index()

使用 str.find() 方法查找子字符串时,如果子字符串不存在于原字符串中,find() 方法不会报错,而是返回 -1str.index()在找不到子字符串时会抛出 ValueError 异常。

str.find()

s = "Hello, World!"
index = s.find("World")
print(index)  # 输出: 7

# 查找不存在的子字符串
index = s.find("Python")
print(index)  # 输出: -1

str.index()

s = "Hello, World!"
index = s.index("World")
print(index)  # 输出: 7

# 查找不存在的子字符串,会抛出 ValueError
try:
    index = s.index("Python")
except ValueError:
    print("Substring not found")  # 输出: Substring not found
  • str.find(substring):返回子字符串在原字符串中的最低索引,如果找不到则返回 -1
  • str.index(substring):返回子字符串在原字符串中的最低索引,如果找不到则抛出 ValueError
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小鱼爱吃火锅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值