python 常用字符串方法
时间: 2025-02-23 18:27:25 浏览: 38
### 常用 Python 字符串方法
#### 处理字符串表示形式
在 Python 中,当在一个交互式编程环境中输入表达式时,Python 自动使用 `repr()` 函数来处理这些表达式[^1]。这有助于开发者获得对象的“官方”字符串表示。
#### 格式化字符串
对于字符串格式化操作,`f-string` 提供了一种简洁而直观的方法来嵌入表达式的值到字符串中。例如:
```python
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
```
另一种方式是通过 `str.format()` 方法实现更灵活复杂的格式控制[^2]:
```python
greeting = "{} is {} years old.".format(name, age)
print(greeting)
```
#### 删除空白字符
为了去除字符串两端不必要的空格或其他指定字符,可以分别调用 `strip()`, `lstrip()`, 或者 `rstrip()` 方法。下面的例子展示了如何移除特定字符:
```python
heading = 'Section 1. Issue #15.....'
new_heading = heading.rstrip('.#')
print(new_heading) # 输出: Section 1. Issue 15
```
此代码片段说明了 `rstrip()` 可用于清除位于字符串结尾处给定集合内的任意数量连续出现的目标字符[^3]。
#### 查找子串位置
利用 `find()` 和 `index()` 来定位某个子串首次出现的位置;区别在于如果找不到目标,则前者返回 `-1` 而后者抛出异常。
```python
text = "hello world"
position_of_o = text.find('o') # 返回第一次出现'o'的位置索引
try:
position_of_z = text.index('z') # 如果不存在则引发ValueError
except ValueError as e:
print(e)
```
#### 替换部分文本
要将原字符串里的某些模式替换成新的内容,可借助于 `replace(old, new[, count])` 方法完成整个或有限次数替换工作。
```python
old_text = "one plus one equals two"
replaced_text = old_text.replace("one", "1").replace("two", "2")
print(replaced_text) # 结果为:"1 plus 1 equals 2"
```
#### 切分与连接多个字符串
- **分割**: 使用 `split([sep[, maxsplit]])` 将大段文字按照指定分隔符拆分成列表;
- **拼接**: 对一系列项应用 `''.join(iterable)` 实现高效组合成单个整体。
```python
sentence = "This,is,a,test"
words_list = sentence.split(',') # ['This', 'is', 'a', 'test']
joined_sentence = '-'.join(words_list)
print(joined_sentence) # This-is-a-test
```
阅读全文
相关推荐














