比如说,
line = "array[0] is the first element, array[0]some_character, is not a valid element"
我只想找到并替换字符串中的"array[0]"
。在本例中,假设我想用单词"element1"
替换它。然后输出应如下所示:
line = "element1 is the first element, array[0]some_character, is not a valid element".
请注意,在字符串中,array[0]some_character
应该保持不变,不应该像"element1some_character"
那样替换它
我感谢任何人的帮助
输出:
说明:
Demo & explanation
试着跟随
输出:
'abcd ab[0]c ahmed class ab[0]d classified ahmed'
或者使用前瞻性
输出:
'abcd ab[0]c ahmed class ab[0]d classified ahmed'
t = "array[0] is the first element, array[0]some_character, is not a valid element" re.sub("a[a-z]+\[[0-9]+\](?=[\s]{1})", "Element1", t)
您可以看到,在regex-(?=[\s]{1})的末尾,第二个数组[0]后面没有空格,因此它不会被替换
相关问题 更多 >
编程相关推荐