# 示例1:创建字符串
# 使用单引号或双引号创建字符串
s1 = 'Hello, world!'
s2 = "Python is fun!"
print(s1) # 输出: Hello, world!
print(s2) # 输出: Python is fun!
# 示例2:字符串拼接
# 使用 + 操作符拼接字符串
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message) # 输出: Hello, Alice!
# 示例3:字符串格式化
# 使用 f-string 进行格式化
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # 输出: My name is Alice and I am 25 years old.
# 示例4:字符串方法
# 使用常用字符串方法如 upper(), lower(), strip(), replace() 等
text = " hello world "
print(text.upper()) # 输出: " HELLO WORLD "
print(text.lower()) # 输出: " hello world "
print(text.strip()) # 输出: "hello world"
print(text.replace("world", "Python")) # 输出: " hello Python "
# 示例5:字符串索引和切片
# 使用索引和切片操作字符串
alphabet = "abcdefghijklmnopqrstuvwxyz"
print(alphabet[0]) # 输出: 'a'
print(alphabet[-1]) # 输出: 'z'
print(alphabet[0:5]) # 输出: 'abcde'
print(alphabet[-5:]) # 输出: 'vwxyz'
下一篇:python 除法取整
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站