简体   繁体   中英

How to exactly match a word and then replace in Python?

  1. Have a list which contains strings etc. as shown below

    strpool = ['fruit,apple:3', '', '[1,abcd, ['fruit,apple'], ['1,kdlld', apple,taste]]']
  2. Wanted to search exactly for the word 'apple' and replace with 'apple:3'

  3. I tried the below code,

     print str(strpool).replace("apple","apple:3") print (re.sub(r"\\bapple\\b","apple:3",str(strpool)))
  4. But its replacing even the apple:3 as well into apple:3:3 , not just the string apple.

  5. Thought apple:3 would be considered as a string and that doesn't get changed.

Update: How can I exactly match a string name without any other components attached to it and replace all of them inside a list ?

Tried re.sub but for that need to convert the list to string, instead is there any other way ?

使用否定前瞻来匹配一个单词,除非它后面跟有:

print(re.sub(r'\bapple\b(?!:)', 'apple:3', str(strpool))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM