0%

str 字符串数据类型

简介

  • str字符串数据类型相关学习笔记

python3 str字符串类型 详解

在 Python 中,str 类型表示字符串,它是一个 不可变的序列,由零个或多个字符组成。字符串是 Python 中常用的数据类型之一,广泛应用于处理文本数据。

1. 创建字符串

Python 中可以通过几种方式创建字符串:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 单引号
string1 = 'Hello, world!'

# 双引号
string2 = "Hello, Python!"

# 三引号(三单引号或三双引号)用于多行字符串
string3 = '''This is a
multi-line string.'''

# 使用 `str()` 函数转换其他类型为字符串
num = 123
string4 = str(num) # '123'

# 转义字符
string5 = "Hello\nworld!" # 包含换行符

2. 访问字符串中的字符

由于字符串是序列类型,可以通过索引访问字符,索引从 0 开始。负数索引表示从右边开始计数。

1
2
3
4
5
6
7
8
9
string = "Hello"

# 正向索引
print(string[0]) # 输出 'H'
print(string[1]) # 输出 'e'

# 负向索引
print(string[-1]) # 输出 'o'
print(string[-2]) # 输出 'l'

3. 切片操作

你可以使用切片来提取字符串的一部分。

1
2
3
4
5
6
7
8
string = "Hello, Python!"

# 切片:string[start:end:step]
print(string[0:5]) # 输出 'Hello'
print(string[7:13]) # 输出 'Python'
print(string[:5]) # 输出 'Hello'
print(string[7:]) # 输出 'Python!'
print(string[::2]) # 输出 'Hoo yhn'
  • **start**:切片开始的索引(包含)。
  • **end**:切片结束的索引(不包含)。
  • **step**:步长,可以为负数。

4. 字符串的连接与重复

你可以使用 + 来连接字符串,或者使用 * 来重复字符串。

1
2
3
4
5
6
7
# 字符串连接
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2 # 输出: "Hello World"

# 字符串重复
result2 = "Hello " * 3 # 输出: "Hello Hello Hello "

5. 字符串常用方法

5.1 len()

返回字符串的长度(字符数)。

1
2
string = "Hello"
print(len(string)) # 输出: 5

5.2 upper()lower()

将字符串转换为大写或小写。

1
2
3
string = "Hello"
print(string.upper()) # 输出: "HELLO"
print(string.lower()) # 输出: "hello"

5.3 strip()

移除字符串两端的空白字符(包括换行符、空格等)。

1
2
string = "  Hello, World!  "
print(string.strip()) # 输出: "Hello, World!"

5.4 replace()

替换字符串中的指定子字符串。

1
2
string = "Hello, World!"
print(string.replace("World", "Python")) # 输出: "Hello, Python!"

5.5 split()

根据指定分隔符拆分字符串,返回一个列表。

1
2
string = "Hello, Python, World!"
print(string.split(", ")) # 输出: ['Hello', 'Python', 'World!']

5.6 join()

将列表中的元素连接为一个字符串,并使用指定分隔符。

1
2
words = ["Hello", "Python", "World"]
result = ", ".join(words) # 输出: "Hello, Python, World"

5.7 find()index()

查找子字符串的索引,find() 返回 -1 如果未找到,而 index() 会抛出 ValueError

1
2
3
string = "Hello, Python!"
print(string.find("Python")) # 输出: 7
print(string.index("Python")) # 输出: 7

5.8 startswith()endswith()

检查字符串是否以指定的前缀或后缀开始或结束。

1
2
3
string = "Hello, Python!"
print(string.startswith("Hello")) # 输出: True
print(string.endswith("!")) # 输出: True

5.9 isdigit()isalpha()

判断字符串是否只包含数字或字母。

1
2
3
4
5
string1 = "123"
string2 = "abc"

print(string1.isdigit()) # 输出: True
print(string2.isalpha()) # 输出: True

5.10 count()

统计某个子字符串在字符串中出现的次数。

1
2
string = "Hello, Hello, Hello!"
print(string.count("Hello")) # 输出: 3

5.11 casefold()

返回一个标准化的字符串,常用于大小写比较。

1
2
3
string1 = "HELLO"
string2 = "hello"
print(string1.casefold() == string2.casefold()) # 输出: True

6. 字符串格式化

6.1 f-string (Python 3.6+)

Python 3.6 引入了 f-string,提供了一个简洁的格式化方式:

1
2
3
4
name = "Python"
version = 3.9
formatted = f"Welcome to {name} {version}!"
print(formatted) # 输出: Welcome to Python 3.9!

6.2 format()

1
2
formatted = "Welcome to {} {}!".format(name, version)
print(formatted) # 输出: Welcome to Python 3.9!

6.3 % 格式化

这种方法已经不太推荐使用,但仍然可以见到:

1
2
formatted = "Welcome to %s %s!" % (name, version)
print(formatted) # 输出: Welcome to Python 3.9!

7. 字符串的不可变性

Python 的 str 类型是 不可变的,这意味着一旦字符串创建后,它的内容无法被修改。如果你修改字符串的内容,实际上会创建一个新的字符串对象。

1
2
3
4
string = "Hello"
# 修改字符串(实际上是创建了一个新的字符串)
string = string + " World!"
print(string) # 输出: "Hello World!"

8. 字符串的编码与解码

Python 字符串通常是 Unicode 字符串,但它也可以通过编码和解码与字节数据进行交互。

1
2
3
4
5
6
7
8
# 编码
string = "Hello, 世界"
encoded = string.encode("utf-8")
print(encoded) # 输出: b'Hello, \xe4\xb8\x96\xe7\x95\x8c'

# 解码
decoded = encoded.decode("utf-8")
print(decoded) # 输出: Hello, 世界

9. 字符串的应用场景

  • 文本处理:如分词、查找、替换等。
  • 用户输入与输出:处理用户输入的文本数据。
  • 数据格式转换:如 JSON 或 CSV 格式的解析与生成。
  • 文件操作:读取和写入文本文件。

10. 总结

  • 字符串类型(str 在 Python 中非常重要,广泛应用于文本处理。
  • 不可变性:字符串一旦创建,不能修改。
  • Python 提供了丰富的字符串方法,能够轻松完成查找、替换、切割、格式化等常见任务。
  • 编码和解码:Python 字符串默认使用 Unicode 编码,支持多种编码方式。

这些操作和方法使得字符串在 Python 中非常灵活和强大。

感谢老板支持!敬礼(^^ゞ