Python:除了以数字开头的字符串外,是否有一行脚本来命名大小写字符串?
Python:除了以数字开头的字符串外,是否有一行脚本来命名大小写字符串?,python,title-case,Python,Title Case,title() 数字的数量可以是可变的,而且并不总是有数字。下面是每个案例的一个例子 "this is sparta".title() # This Is Sparta "3rd sparta this is".title() # 3Rd Sparta This Is "4545numbers start here".title() # "4545Numbers Start Here 我希望将这些更改为: "This Is Sparta" "3rd Sparta This Is" "4
title()
数字的数量可以是可变的,而且并不总是有数字。下面是每个案例的一个例子
"this is sparta".title() # This Is Sparta
"3rd sparta this is".title() # 3Rd Sparta This Is
"4545numbers start here".title() # "4545Numbers Start Here
我希望将这些更改为:
"This Is Sparta"
"3rd Sparta This Is"
"4545numbers Start Here"
我使用的程序不允许导入,我需要在一行中完成。我唯一可以使用的库是re
如果可能的话,我倾向于使用列表理解来完成这项工作。这里有一个简单的列表理解:
' '.join([word.capitalize() for word in your_string.split(' ')])
如果您想在标点符号和其他空格上拆分,您可能必须使用某种re
功能。这可能是另一种选择:
s = "3rd sparta this is"
" ".join([si.title() if not (str.isdigit(si[0])) else si for si in s.split()])
只需将第一个字符设置为大写
string = string.split (' ')
for x in range (len(string)):
try:
string[x] = string[x][0].uppercase() + string [x][1:]
except ValueError:
pass
temp = ''
for word in string:
temp += word + ' '
string = temp
string.title()
事实证明,已经有一个函数可以做到这一点:
需要注意的一件事是:所有的空格将被压缩到一个空格中,并且前导空格和尾随空格将被删除。值得注意的是,这意味着您将丢失行分隔符。如果希望保留这些行,则应首先将其拆分为多行
请注意,在内部,它实际上使用了大写
方法而不是标题
,但这似乎是您想要的。正则表达式解决方案
In [19]: re.sub(r'\b(\w+)\b', lambda x: x.groups()[0].capitalize(), "3rd sparta this.is1", re.UNICODE)
Out[19]: '3rd Sparta This.Is1'
(请参阅文档)@rcoyner具有讽刺意味的是,我之所以找到它,是因为我正在查找文档中的split
,以获取您的答案。lolI会注意到,word[0].upper()+word[1://code>并不完全等同于title
。示例:'ABCD'[0]。upper()+'ABCD'[1://code>是'ABCD'
,而'ABCD'.title()
是'ABCD'
。我认为将word[1:][/code>更改为word[1:][.lower()
可以解决这个问题,但在这一点上,你也可以将大写改为。呃,字符串.capwords
解决方案是最好的,所以谁在乎呢编辑:您的string.capwords
solution:)看起来像是OP在编辑/注释中指定,出于某种奇怪的原因,他们在导入时遇到了问题,因此在这种情况下,您的方法实际上可能更好。;)这就是我想要的答案。我想我应该指定我想使用列表理解。我无法使用导入,因为表达式是在Python上下文中计算的,只有一行。等等,是谁否决了这一点???/为什么????为什么没有进口条款?标准库导入(如re)应该已经在sys.modules中。尝试导入系统;我不知道为什么。我在外部程序中使用python,而不是自定义脚本,这就是为什么我不能使用import
。当尝试使用string
时,我得到namererror:“string未定义”
当然它应该可以访问标准库吗?这是什么翻译?我可以理解不加载非标准库的必要性,但通常像re这样的模块是在启动时加载的。(例如,Jython、CPython和PyPy)我必须询问开发人员。所有标准模块都可以导入,但是在一行参数中,没有导入语句,我相信string
对于程序来说就像一个未定义的变量。这正是我想要的。
In [19]: re.sub(r'\b(\w+)\b', lambda x: x.groups()[0].capitalize(), "3rd sparta this.is1", re.UNICODE)
Out[19]: '3rd Sparta This.Is1'