Python——字符串处理
时间: 2025-02-28 07:09:08 浏览: 37
### Python 字符串处理方法和函数
#### 字符串定义
字符串是 Python 中最常用的数据类型之一,它们可以用单引号或双引号来表示[^1]。
```python
single_quoted_string = 'Hello, world!'
double_quoted_string = "Hello, universe!"
```
#### 基本字符串操作函数
##### 拼接字符串
可以通过加号 `+` 来实现两个字符串的拼接:
```python
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name # 输出: Hello, Alice
```
##### 分割字符串
使用 `split()` 函数可以根据指定分隔符将字符串分割成列表:
```python
text = "apple,banana,cherry"
fruits = text.split(",") # ['apple', 'banana', 'cherry']
```
##### 查找子串位置
利用 `find()` 或者 `index()` 可以找到某个子串首次出现的位置;如果找不到,则 `find()` 返回 `-1` 而 `index()` 抛出异常:
```python
sentence = "Welcome to the jungle."
position_find = sentence.find("jungle") # position_find=11
try:
position_index = sentence.index("desert")
except ValueError as e:
print(e) # substring not found
```
##### 替换子串
通过 `replace(old, new)` 将旧子串替换成新子串:
```python
old_text = "I like cats and dogs."
new_text = old_text.replace("cats", "rabbits") # I like rabbits and dogs.
```
##### 大小写转换
支持多种大小写的转换方式,比如全部大写、首字母大写等:
```python
lowercase = "hello".upper() # HELLO
uppercase = "WORLD".lower() # world
capitalized = "john doe".capitalize() # John doe
titlecased = "john DOE".title() # John Doe
```
#### 特殊字符处理
##### 去除空白字符
为了去除字符串两端多余的空格或其他空白字符,可以采用 `strip()` 方法。此方法会移除开头和结尾处所有的空白字符(包括空格、制表符 `\t` 和换行符 `\n`),但不会影响中间部分的任何空白字符[^2]。
```python
trimmed_string = ' hello there! '.strip()
print(trimmed_string) # hello there!
```
#### 序列转字符串
当有一个由多个项组成的序列并希望将其组合成单一字符串时,可借助于 `join()` 方法。该方法接收一个迭代器作为参数,并用给定的分隔符把各个元素连在一起形成一个新的字符串对象[^3]。
```python
words_list = ["Python", "is", "awesome"]
joined_sentence = "-".join(words_list)
print(joined_sentence) # Python-is-awesome
```
阅读全文
相关推荐
















