2014-09-03 53 views
0

報價如果我想從詞語,如這些刪除引號:刪除與條件

don't 
hello' 
world' 

如何讓這個我只能去除從第二和第三一個報價。即我想要讓我只剝離報價,如果它不是由兩個字母所包圍,並有一個這樣的最終結果是:

don't 
hello 
world 

希望這是有道理的。

回答

0

試試這個:

words = ["don't", "hello'", "world'"] 
quotes = ["'", '"'] 
output = list() 

for word in words: 
    if word[-1] in quotes: 
     word = word[: (len(word) - 1)] 
    output.append(word) 

print output 
#=> ["don't", "hello", "world"] 

我假設你也想處理的情況下不必要的報價庫侖除了單引號之外,d也可以是雙引號,"。如果沒有,你可以只使用:

if word[-1] === "'": 
0

你可以用regex這樣做,但它確實不需要它。讓我知道,如果這是你的問題的innacurate治療,但好像你可以做線沿線的東西:

if not test_string.endswith("'"): 
    test_string.replace("'", "") 

如果你真的想使用regex(這可能是一個不錯的選擇取決於你應用程序),你可以做這樣的事情:

import re 
re.sub('(?:(?<=\w)[\'\"](?:\W))|(?:(?<=\W)[\'\"](?:\w))', '', test_string) 
1

你可以試試這個:

string = "hello'" 

if string[-1] == "'": 
    string = string[:len(string) - 2]