2016-01-27 11 views
-4

我有不同的字符串這樣的:Python的更換不同的字符

"/table[1]/tr/td[2]/table[2]/tr/td[2]/p/b/text()" 
"/table[1]/tr/td[2]/table[3]/tr/td[2]/p/b/text()" 

我想改變的子"/table[" + some number + "]""/table[" + the same number + "]/tbody"

例如,這串

"/table[1]/tr/td[2]/table[2]/tr/td[2]/p/b/text()" 

"/table[1]/tbody/tr/td[2]/table[2]/tbody/tr/td[2]/p/b/text()" 
+4

你嘗試過什麼嗎? – depperm

+1

很快就會出現這樣的問題 - 「我需要這個和那個,你必須爲我提供最好的解決方案」 – tinySandy

+0

對不起,這是我的第一個問題,我已經嘗試了幾件事,沒有因爲他們不工作而在這裏寫下來 –

回答

1

使用symbolic group naming改變,這種方式:

>>> s 
'/table[1]/tr/td[2]/table[2]/tr/td[2]/p/b/text()' 
>>> 
>>> re.sub(r'(?P<table>/table\[\d+\])', r'\g<table>/tbody', s) 
'/table[1]/tbody/tr/td[2]/table[2]/tbody/tr/td[2]/p/b/text()' 
>>> 
>>> #similarly you can also reference by group number 
>>> re.sub(r'(?P<table>/table\[\d+\])', r'\g<1>/tbody', s) 
'/table[1]/tbody/tr/td[2]/table[2]/tbody/tr/td[2]/p/b/text()' 

Python Doc報價:

(?P<name>...)
與常規圓括號類似,但與組匹配的子字符串 可通過符號組名稱名訪問。 組名必須是有效的Python標識符,並且每個組名必須在正則表達式中僅定義一次 。一個符號組是 也是一個編號組,就好像該組沒有被命名一樣。

0

這是解決方案:

import re 

s = "/table[1]/tr/td[2]/table[2]/tr/td[2]/p/b/text()" 
sl = s.split("/") 

new_str = [] 
for n in sl : 
    match = re.search(r'table\[(?P<num>\d+)\]$', n) 
    if match != None : 
     #if you want to get the num 
     #num = match.group('num') 
     new_str.append("{}/tbody".format(n)) 
    else : 
     new_str.append(n) 

print "/".join(new_str)