Python 字符串学习笔记

在 Python 中,字符串是一种不可变的序列数据类型。它们被定义为由一系列字符组成的字符集合。在本文档中,我们将探讨 Python 字符串的常见操作和实例。

创建字符串

可以使用单引号或双引号来创建字符串,并且可以在字符串中包含任何字符,包括数字、字母、符号和空格。例如:

pythonCopy Code
# 使用单引号创建字符串 single_quotes_str = 'This is a string.' # 使用双引号创建字符串 double_quotes_str = "This is another string."

访问字符串中的字符

可以通过使用索引和切片来访问字符串中的字符。每个字符都有一个对应的索引值,第一个字符的索引值为 0。例如:

pythonCopy Code
my_string = "Hello, World!" # 访问第一个字符 first_char = my_string[0] # 访问最后一个字符 last_char = my_string[-1] # 切片访问字符串 substring = my_string[7:]

字符串拼接

可以使用加号 (+) 将两个字符串拼接在一起。例如:

pythonCopy Code
string1 = "Hello" string2 = "World" # 使用加号拼接字符串 result = string1 + " " + string2

字符串格式化

可以使用字符串格式化操作符(%)来插入变量的值。例如:

pythonCopy Code
name = "Alice" age = 25 # 使用字符串格式化操作符来生成字符串 output_string = "My name is %s and I am %d years old." % (name, age)

在 Python 3 中,可以使用 format() 方法来格式化字符串:

pythonCopy Code
name = "Alice" age = 25 # 使用 format() 方法来生成字符串 output_string = "My name is {} and I am {} years old.".format(name, age)

字符串方法

Python 提供了许多有用的字符串方法。以下是一些常见的方法及其用法:

  • upper():将字符串转换为大写字母
  • lower():将字符串转换为小写字母
  • strip():删除字符串中的空格
  • replace():替换字符串中的一个子串
  • split():将字符串拆分成一个列表,列表中的每个元素是一个子字符串
pythonCopy Code
my_string = " Hello, World! " # 将字符串转换为大写字母 uppercase_string = my_string.upper() # 将字符串转换为小写字母 lowercase_string = my_string.lower() # 删除字符串中的空格 stripped_string = my_string.strip() # 替换字符串中的一个子串 replaced_string = my_string.replace("World", "Python") # 将字符串拆分成一个列表 split_string = my_string.split(",")

实例

计算字符串长度

pythonCopy Code
my_string = "Hello, World!" length = len(my_string) print(length) # 输出:13

判断字符串是否包含某个子串

pythonCopy Code
my_string = "Hello, World!" if "World" in my_string: print("The string contains 'World'.") # 输出:The string contains 'World'.

反转字符串

pythonCopy Code
my_string = "Hello, World!" reversed_string = my_string[::-1] print(reversed_string) # 输出:!dlroW ,olleH

将列表中的字符串拼接成一个字符串

pythonCopy Code
my_list = ["Hello", "World", "!"] result = " ".join(my_list) print(result) # 输出:Hello World !

字符串去重

pythonCopy Code
my_string = "Hello, World!" unique_chars = set(my_string) print(unique_chars) # 输出:{',', 'o', 'H', 'W', 'r', '!', 'l', 'd', 'e', ' '}

以上是 Python 字符串的一些常见操作和实例。希望这些内容能够帮助你更好地理解 Python 中的字符串。