在大写字母前插入空格的pythonic方法 [英] A pythonic way to insert a space before capital letters

查看:33
本文介绍了在大写字母前插入空格的pythonic方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,我正在通过 python 脚本更改其格式.我在这个文件中有几个驼峰式字符串,我只想在大写字母前插入一个空格 - 所以WordWordWord"变成了Word Word Word".

我有限的正则表达式经验刚刚在我身上停滞不前 - 有人可以想到一个像样的正则表达式来做到这一点,或者(更好)有没有更pythonic的方法来做到这一点,我想念?

解决方案

你可以试试:

<预><代码>>>>re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord")'字字字'

I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".

My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?

解决方案

You could try:

>>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord")
'Word Word Word'

这篇关于在大写字母前插入空格的pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆