sk1*_*k11 0 python regex string str-replace
我试图在字符串中找到所有大写字母,并用小写加underscore字符替换它.AFAIK没有标准的字符串函数来实现这个(?)
例如,如果输入字符串是'OneWorldIsNotEnoughToLive'输出字符串应该是'_one_world_is_not_enough_to_live'
我能用以下代码完成:
# This finds all the uppercase occurrences and split into a list
import re
split_caps = re.findall('[A-Z][^A-Z]*', name)
fmt_name = ''
for w in split_caps:
fmt_name += '_' + w # combine the entries with underscore
fmt_name = fmt_name.lower() # Now change to lowercase
print (fmt_name)
Run Code Online (Sandbox Code Playgroud)
我觉得这太过分了.首先re,然后是列表迭代,最后转换为小写.也许有一种更简单的方法来实现这一点,更多的pythonic和1-2行.
请建议更好的解决方案 谢谢.
为什么不是一个简单的正则表达式:
import re
re.sub('([A-Z]{1})', r'_\1','OneWorldIsNotEnoughToLive').lower()
# result '_one_world_is_not_enough_to_live'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7475 次 |
| 最近记录: |