我有以下说明
In [362]: !cat data.md
**File Permission Related Commands**
These commands are used to change permissions of the files
```
72. chmod octal file-name : Changes the permissions of file to octal
chmod 777 /data/test.c : Sets rwx permission for owner , group and others
```
**Network Related Commands**
These commands are used to view and edit network configurations related aspects of the system
```
75. ifconfig -a : Displays all network interface and set ip address
我想用```python```标记``````,
所以我应该将开头```更改为```python
In [363]: f = open("data.md", "r+")
In [364]: data = f.read()
In [365]: import re
In [366]: re.sub(r"^(```)", "```bash", data)
Out[366]: '**File Permission Related Commands**\n\nThese commands are used to change permissions of the files\n\n```\n72. chmod octal file-name \t\t : Changes the permissions of file to octal\n chmod 777 /data/test.c
但是,什么都没有改变。
我怎么完成它?
答案 0 :(得分:2)
^
在正常模式下匹配字符串的开头。要使其与行的开头匹配,请将re.MULTILINE
传递到re.sub
re.sub(r"^(```)", "```bash", data, flags=re.MULTILINE)
编辑:只正确替换开头的配对对
re.sub(r'```([^`]+)```', r'```bash\1```', data)
# don't actually need ^ and MULTILINE in your example