1.字符串的格式化输出:
- f-string 是一种方便的字符串格式化方式,可以直接在字符串中嵌入变量。2. name = "Alice" age = 30 print(f"My name is {name} and I am {age} years old.")
2.索引和切片:
- 索引和切片是用来访问字符串中的特定字符或子串的常用方法。 s = "Hello, World" print(s[0]) # 输出:H print(s[7:]) # 输出:World
3. 7个字符串函数的使用
- upper(): 将字符串转换为大写,忽略大小写时使用。- s = "hello" print(s.upper()) # 输出:HELLO
- replace(): 替换字符串中的特定内容。- s = "apple" new_s = s.replace("p", "m") print(new_s) # 输出:amme
- split(): 将字符串分割成列表。- s = "apple,banana,cherry" items = s.split(",") print(items) # 输出:['apple', 'banana', 'cherry']
- join(): 拼接列表的内容成为新字符串。- items = ['apple', 'banana', 'cherry'] s = "-".join(items) print(s) # 输出:apple-banana-cherry
- startswith(): 判断字符串是否以指定内容开头。- s = "Hello, World" print(s.startswith("Hello")) # 输出:True