算法与数据结构 (Algorithms and Data Structures)

字符串(5)

Posted by 月月鸟 on September 17, 2021

字符串定义

在Python中,字符串(String)是一种用于表示文本的数据类型。字符串由字符组成,可以使用单引号 (')、双引号 (") 或三重引号 ('''""") 来创建。三重引号用于表示多行字符串。

创建字符串

# 单引号创建字符串
single_quote_str = 'Hello, World!'

# 双引号创建字符串
double_quote_str = "Python Programming"

# 三重引号创建多行字符串
triple_quote_str = """This is a string
that spans multiple lines."""

字符串常见操作

1. 字符串拼接

字符串拼接是将多个字符串合并为一个字符串。

str1 = 'Hello'
str2 = 'World'
result = str1 + ' ' + str2
print(result)  # 输出: Hello World

2. 字符串重复

使用 * 操作符重复字符串。

echo = 'Hello! ' * 3
print(echo)  # 输出: Hello! Hello! Hello! 

3. 字符串格式化

格式化字符串可以让我们插入变量到字符串中。Python 提供了多种格式化方法。

  • f-string(格式化字符串字面量)(Python 3.6+)
name = 'Alice'
age = 30
formatted_str = f'Name: {name}, Age: {age}'
print(formatted_str)  # 输出: Name: Alice, Age: 30
  • str.format() 方法
template = 'Name: {}, Age: {}'
formatted_str = template.format(name, age)
print(formatted_str)  # 输出: Name: Alice, Age: 30
  • 旧式 % 格式化
formatted_str = 'Name: %s, Age: %d' % (name, age)
print(formatted_str)  # 输出: Name: Alice, Age: 30

4. 字符串切片

切片用于提取字符串的一部分。

text = 'Python Programming'
substring = text[7:18]  # 从索引7到索引17(不包括18)
print(substring)  # 输出: Programming

# 切片也可以使用负索引
substring = text[-11:]  # 从倒数第11个字符到末尾
print(substring)  # 输出: Programming

5. 字符串方法

  • 去除空白字符
text = '  hello world  '
clean_text = text.strip()  # 去除两端空白
print(clean_text)  # 输出: hello world
  • 转换大小写
text = 'Python Programming'
print(text.upper())  # 输出: PYTHON PROGRAMMING
print(text.lower())  # 输出: python programming
  • 替换子字符串
text = 'I love Python'
new_text = text.replace('Python', 'programming')
print(new_text)  # 输出: I love programming
  • 查找子字符串
text = 'Python is great'
index = text.find('great')  # 返回子字符串的开始索引
print(index)  # 输出: 11

# 如果找不到子字符串,find() 返回 -1
index = text.find('Java')
print(index)  # 输出: -1
  • 切分字符串
text = 'Python,Java,C++,JavaScript'
words = text.split(',')
print(words)  # 输出: ['Python', 'Java', 'C++', 'JavaScript']
  • 连接字符串
words = ['Python', 'is', 'fun']
sentence = ' '.join(words)
print(sentence)  # 输出: Python is fun

字符串编码和解码

在处理文本时,了解字符串的编码和解码也是很重要的。

  • 编码(将字符串转换为字节)
text = 'Hello'
encoded_text = text.encode('utf-8')
print(encoded_text)  # 输出: b'Hello'
  • 解码(将字节转换为字符串)
decoded_text = encoded_text.decode('utf-8')
print(decoded_text)  # 输出: Hello

字符串运算符

  • 检查是否包含子字符串
text = 'Python Programming'
contains_python = 'Python' in text
print(contains_python)  # 输出: True
  • 字符串长度
text = 'Python'
length = len(text)
print(length)  # 输出: 6