3. 假设有一段英文‘i am a bird, i am a fruit, and i am happy. I am not a dog.‘。其中单独的字母I误写为i,请编写程序进行纠正。(两种方法,其中一种为正则表达式)python
时间: 2023-06-11 19:10:33 浏览: 105
【python】——正则表达式(csdn)————程序.pdf
方法一:使用字符串替换函数replace()
```python
string = 'i am a bird, i am a fruit, and i am happy. I am not a dog.'
corrected_string = string.replace(' i ', ' I ')
print(corrected_string)
```
输出结果为:
```
I am a bird, I am a fruit, and I am happy. I am not a dog.
```
方法二:使用正则表达式进行替换
```python
import re
string = 'i am a bird, i am a fruit, and i am happy. I am not a dog.'
corrected_string = re.sub(r'\bi\b', 'I', string)
print(corrected_string)
```
输出结果为:
```
I am a bird, I am a fruit, and I am happy. I am not a dog.
```
在正则表达式中,`\b`表示单词边界,`\b i \b`表示匹配单独的字母i。`re.sub()`函数用于替换字符串中匹配正则表达式的部分。
阅读全文