这里给出Python 3.4.2代码,如果使用Python 2.7.8的话只需要修改其中的print()函数为print语句即可。
1)不使用正则表达式 x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman."
x = x.replace('i ','I ')
x = x.replace(' i ',' I ')
print(x)
2)使用正则表达式 x = "i am a teacher,i am man, and i am 38 years old.I am not a businessman."
import re
pattern = re.compile(r'(?:[^\w]|\b)i(?:[^\w])')
while True:
result = pattern.search(x)
if result:
if result.start(0) != 0:
x = x[:result.start(0)+1]+'I'+x[result.end(0)-1:]
else:
x = x[:result.start(0)]+'I'+x[result.end(0)-1:]
else:
break
print(x)