Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
仅当模式出现在字符串的开头时才替换它。例如str1 = "abab abadfadsf"
str1 = "abab abadfadsf"
我只想删除/替换 str1 开头的“ab”,即我想编写一个正则表达式,以便我可以str2 = "ab abadfadsf"从 str1获取re.sub
str2 = "ab abadfadsf"
re.sub
我该怎么做?
对于这种简单的情况,您最好使用内置的字符串方法 - 正则表达式对于更复杂的匹配很有用,但不是必需的。
str2 = str1[2:] if str1.startswith('ab') else str1
您可以使用re.sub('^ab', '', 'abab abadfadsf') ^代表字符串的开头。
re.sub('^ab', '', 'abab abadfadsf')
^