【发布时间】:2017-12-28 12:58:48
【问题描述】:
我想用与较长字符串中的模式匹配的子字符串做一些事情(不仅仅是替换)。如果赋值是一个返回值的表达式,就像在 C 和大多数其他编程语言中一样,这将是(使用带有 Python 语义的 C 语法):
while ( match = re.search( pat, str ) ) {
/* do something to the string, using the match object,
in addition to removing or replacing the substring
*/
}
或者更冗长,避免使用赋值作为表达式:
for ( match = re.search( pat, str );
match;
match = re.search( pat, str ) ) {
/* do something to the string, using the match object */
}
在大多数编程语言中至少有一种是可能的:C、C++、Java、Perl、Javascript,...但它们似乎都不可能在 Python 中实现。是否有 python 等效项(不涉及带有 break 或 continue 语句的混乱混乱)?
【问题讨论】:
-
答案取决于。你在循环什么?绝对没有一对一的映射,但肯定有 pythonic 等价物。如果您可以更精确地了解您想要的内容...因为就目前而言,这个问题太宽泛了。
标签: python for-loop while-loop