Python字符串处理:切片、替换和格式化案例
在Python中,字符串是一种不可变对象,但是我们可以通过各种方法来操作它们。以下是关于切片、替换和格式化的几个案例:
切片:
- 获取子串:
s = "Hello, World!"
,print(s[7:12]))
输出World!
- 跳过或包含多个字符范围:
print(s[0:5] + s[12:])))
输出Hello, World!
- 获取子串:
替换:
- 替换子串:
s = "Python is fun!"
,print(s.replace("is", "was")))
)输出Python was fun!
- 替换子串:
格式化(例如,使用f-string):
- 创建复杂格式的字符串:`name = “Alice”
age = 25
city = "New York"`
print(f"{name}, you are {age} years old and live in {city}.")")
输出:
Alice, you are 25 years old and live in New York.
- 创建复杂格式的字符串:`name = “Alice”
以上就是Python字符串处理中的切片、替换和格式化的一些基本案例。
还没有评论,来说两句吧...