如果字符串以'a'或'the'开头,我想重写CSV行。我们可能会将string.startswith()
用于此目的。
问题可能是这样严重说的:
if string.startswith('A' or 'The')
remove 'a' and 'the'; keep the rest of the string; rewrite the row
假设CSV是:
ID Book Author
1. A Study in Scarlet Conan Doyle
2. Aboltabol Sukumar Roy
3. The Bible Matthew
它应该看起来像:
ID Book Author
1. Study in Scarlet Conan Doyle
2. Aboltabol Sukumar Roy
3. Bible Matthew
我们如何在Python中执行此操作?
使用正则表达式模块
import re
pattern = re.compile("^(A|The)\s+(.+)", flags=re.IGNORECASE)
def process(word):
w = pattern.match(word)
return w.group(2) if w else word
process('A Study in Scarlet') # 'Study in Scarlet'
process('Aboltabol') # 'Aboltabol'
process('The Bible') # 'Bible'
虽然如果你需要表现,startswith
+ split
会更快。