PPZ

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1. 创建字符串

使用引号创建字符串
# 单引号
str1 = 'Hello, World!'
# 双引号
str2 = "Hello, World!"
# 三引号(可用于创建多行字符串)
str3 = '''Hello,
World!'''
str4 = """Hello,
World!"""

2. 基本操作

字符串连接
str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2 + "!"
print(result)  # 输出: Hello, World!
字符串重复
str1 = "Hello"
result = str1 * 3
print(result)  # 输出: HelloHelloHello
获取字符串长度
str1 = "Hello, World!"
length = len(str1)
print(length)  # 输出: 13

3. 字符串索引和切片

访问单个字符
str1 = "Hello, World!"
char = str1[7]
print(char)  # 输出: W
字符串切片
str1 = "Hello, World!"
substring = str1[7:12]
print(substring)  # 输出: World

# 省略起始索引,默认从0开始
substring = str1[:5]
print(substring)  # 输出: Hello

# 省略结束索引,默认到字符串末尾
substring = str1[7:]
print(substring)  # 输出: World!

# 使用负索引
substring = str1[-6:-1]
print(substring)  # 输出: World

4. 字符串方法

转换大小写
str1 = "Hello, World!"
print(str1.upper())  # 输出: HELLO, WORLD!
print(str1.lower())  # 输出: hello, world!
print(str1.capitalize())  # 输出: Hello, world!
print(str1.title())  # 输出: Hello, World!
去除空白字符
str1 = "  Hello, World!  "
print(str1.strip())  # 输出: Hello, World!
print(str1.lstrip())  # 输出: Hello, World!  
print(str1.rstrip())  # 输出:   Hello, World!
查找和替换
str1 = "Hello, World!"
print(str1.find('World'))  # 输出: 7
print(str1.find('Python'))  # 输出: -1

print(str1.replace('World', 'Python'))  # 输出: Hello, Python!
拆分和连接
str1 = "Hello, World!"
words = str1.split(', ')
print(words)  # 输出: ['Hello', 'World!']

str2 = '-'.join(words)
print(str2)  # 输出: Hello-World!
判断字符串特性
str1 = "Hello, World!"
print(str1.startswith('Hello'))  # 输出: True
print(str1.endswith('World!'))  # 输出: True
print(str1.isalpha())  # 输出: False
print("Hello".isalpha())  # 输出: True
print("123".isdigit())  # 输出: True
print("abc123".isalnum())  # 输出: True

5. 字符串格式化

使用 % 进行格式化
name = "Alice"
age = 30
str1 = "My name is %s and I am %d years old." % (name, age)
print(str1)  # 输出: My name is Alice and I am 30 years old.
使用 str.format() 方法
name = "Alice"
age = 30
str1 = "My name is {} and I am {} years old.".format(name, age)
print(str1)  # 输出: My name is Alice and I am 30 years old.

str2 = "My name is {0} and I am {1} years old. {0} is learning Python.".format(name, age)
print(str2)  # 输出: My name is Alice and I am 30 years old. Alice is learning Python.
使用 f-string (Python 3.6+)
name = "Alice"
age = 30
str1 = f"My name is {name} and I am {age} years old."
print(str1)  # 输出: My name is Alice and I am 30 years old.

pi = 3.14159
str2 = f"The value of pi is approximately {pi:.2f}."
print(str2)  # 输出: The value of pi is approximately 3.14.
posted on 2024-06-04 20:15  犬卧  阅读(10)  评论(0编辑  收藏  举报