Python 字符串:全面指南(上)126


在 Python 中,字符串是表示文本数据的序列。它们是 Python 中最基本的类型之一,并且在各种应用程序中得到广泛使用。

字符串字面量

字符串字面量是用引号(单引号或双引号)括起来的文本序列。例如:```python
>>> my_string1 = 'Hello, world!'
>>> my_string2 = "This is a string."
```

创建字符串

除了字符串字面量,还可以使用以下方法创建字符串:* str() 函数:将其他数据类型转换为字符串。例如:
```python
>>> my_int = 123
>>> my_string = str(my_int) # my_string 现在包含 "123"
```
* join() 方法:将可迭代对象中的元素连接成一个字符串。例如:
```python
>>> my_list = ['Hello', 'world', '!']
>>> my_string = ''.join(my_list) # my_string 现在包含 "Hello world!"
```

字符串操作

Python 提供了丰富的字符串操作,包括:* 连接:使用 `+` 运算符连接字符串。例如:
```python
>>> my_string1 = 'Hello'
>>> my_string2 = 'world!'
>>> my_string3 = my_string1 + my_string2 # my_string3 现在包含 "Hello world!"
```
* 复制:使用 `*` 运算符复制字符串。例如:
```python
>>> my_string = 'Hello'
>>> my_duplicated_string = my_string * 3 # my_duplicated_string 现在包含 "HelloHelloHello"
```
* 索引:使用方括号获取字符串中的字符。索引从 0 开始。例如:
```python
>>> my_string = 'Hello'
>>> my_first_char = my_string[0] # my_first_char 现在包含 "H"
```
* 切片:使用方括号和冒号获取字符串的一部分。例如:
```python
>>> my_string = 'Hello'
>>> my_slice = my_string[1:4] # my_slice 现在包含 "ell"
```
* 查找:使用 `find()` 或 `index()` 方法在字符串中查找子字符串。例如:
```python
>>> my_string = 'Hello world!'
>>> my_found_index = ('world') # my_found_index 现在包含 6
```
* 替换:使用 `replace()` 方法替换字符串中的子字符串。例如:
```python
>>> my_string = 'Hello world!'
>>> my_replaced_string = ('world', 'Python') # my_replaced_string 现在包含 "Hello Python!"
```
* 大小写转换:使用 `upper()` 和 `lower()` 方法将字符串转换为大写或小写。例如:
```python
>>> my_string = 'Hello'
>>> my_upper_string = () # my_upper_string 现在包含 "HELLO"
>>> my_lower_string = () # my_lower_string 现在包含 "hello"
```

2024-10-24


上一篇:Python 函数的用途和优势简介

下一篇:Python 文件和行号查找