python 字符串高级用法

  1. 字符串格式化:使用 % 或 format 方法将变量插入到字符串中。

示例:

name = "Alice"
age = 25
print("My name is %s, and I am %d years old." % (name, age))
print("My name is {}, and I am {} years old.".format(name, age))

输出:

My name is Alice, and I am 25 years old.
My name is Alice, and I am 25 years old.
  1. 字符串切片:使用索引或切片操作从字符串中取出子字符串。

示例:

s = "Hello, world!"
print(s[0])     # 'H'
print(s[7:12])  # 'world'
  1. 字符串拼接:使用 + 或 join 方法将多个字符串拼接起来。

示例:

s1 = "Hello"
s2 = "world"
s3 = s1 + ", " + s2 + "!"
print(s3)   # 'Hello, world!'
  1. 字符串查找和替换:使用 find、replace、startswith、endswith 等方法查找和替换字符串中的子字符串。

示例:

s = "Hello, world!"
print(s.find("world"))   # 7
print(s.replace("world", "Python"))   # 'Hello, Python!'
print(s.startswith("Hello"))   # True
print(s.endswith("!"))   # True
  1. 字符串分割和连接:使用 split、join 方法对字符串进行分割和连接。

示例:

s = "apple, banana, cherry"
print(s.split(", "))   # ['apple', 'banana', 'cherry']
fruits = ['apple', 'banana', 'cherry']
print(", ".join(fruits))   # 'apple, banana, cherry'

以上是 Python 字符串高级用法的几个示例,还有其他一些高级用法,如字符串格式化表达式、正则表达式等。这些用法可以让我们更加灵活地处理字符串,并且提高了我们的编程效率。

python 字符串高级用法

原文地址: http://www.cveoy.top/t/topic/dvF3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录