2012-08-15 163 views
1

我試圖用以下Python函數替換pimath.pi選擇性的Python字符串替換

def cleanup(x): 
    return x.replace("pi", "math.pi") 

我有以下字符串:

a = "2*pi" 
b = "the pink elephant" 

cleanup(a)的輸出是:2*math.pi - 這非常適用!

cleanup(b)的輸出是the math.pink elephant - 問題:我不希望「文本」發生變化。

有人可以幫助我嗎?

+0

如果你是「從數學進口PI」固定了Python代碼,只是定義和你沒有替代任何東西。現在,Python允許使用Unicode標識符,您還可以將此導入添加到您的代碼中:'從數學導入pi作爲π',然後您可以編寫代碼,如'C =π* D' – PaulMcG 2012-08-15 10:12:23

回答

3

你要找的正則表達式,特別是模塊,在「單詞邊界」(\b)斷言:

import re 
print re.sub(r'\bpi\b', 'math.pi', "2*pi") 
print re.sub(r'\bpi\b', 'math.pi', "the pink elephant") 
+0

一個總是在學習。這將是「手動」的方式:'(?<!\ w)pi(?!\ w)' – Paranaix 2012-08-15 10:15:01

+0

Python中正則表達式的一個很好的資源:http://www.tutorialspoint.com/python/python_reg_expressions.htm – leenremm 2012-08-20 11:19:49