[英]Python convert all-caps into title case without messing with camel case
I'm using python3 and would like to turn strings that contain all caps words (separately or inside a word) into title case (first letter capitalized).我正在使用 python3 并且想将包含所有大写单词(单独或在单词中)的字符串转换为标题大小写(第一个字母大写)。 I do not want to disrupt one-off capital letters in the middle of a word (camel case), but if there are repeated capitalized letters, I want to keep only the first one capitalized.
我不想破坏单词中间的一次性大写字母(驼峰式),但如果有重复的大写字母,我只想保留第一个大写字母。
Here's the desired behavior这是所需的行为
>>> a = "TITLE BY DeSoto theHUMUNGUSone"
>>> print(myfunc(a))
Title By DeSoto TheHumungusone
In words, "capitalize the beginning of each word and then take any letter that follows a capital letter and make it lower case."在单词中,“将每个单词的开头大写,然后将大写字母后面的任何字母变为小写。”
The str.title()
does the initial letters the way I want, but it makes all intra-word letters lower case, rather than just those following the first. str.title()
以我想要的方式处理首字母,但它使所有单词内字母小写,而不仅仅是第一个字母之后的字母。
I was playing with a regular expression approach that makes anything that follows an upper case letter lower case, but I kept getting every other letter capitalized.我正在使用一种正则表达式方法,它将大写字母后面的任何内容变为小写,但我一直将所有其他字母大写。
A regular expression substitution with a lambda is the way to go:用 lambda 替换正则表达式是可行的方法:
import re
a = "TITLE BY DeSoto theHUMUNGUSone"
print(re.sub('[A-Z]+', lambda x: x.group(0).title(), a))
Output:输出:
Title By DeSoto theHumungusone
Haha this sounds like a leetcode problem!哈哈,这听起来像是一个 leetcode 问题! In addition to regex, you could use this little algorithm, which just makes a new string, and iterates through the characters, converting any following to lowercase when an uppercase is hit.
除了正则表达式之外,您还可以使用这个小算法,它只是创建一个新字符串,并遍历字符,当遇到大写字母时将任何后续转换为小写字母。 You can easily modify it to make anything following spaces uppercase also.
您可以轻松修改它以使空格后面的任何内容也大写。
b = ''
i = 0
while i < len(a):
if a[i].isupper():
b += a[i]
for j in range(i + 1, len(a)):
if a[j].isupper():
b += a[j].lower()
else:
i = j - 1
break
else:
b += a[i]
i += 1
how about this one:这个怎么样:
import re
a = "TITLE BY DeSoto theHUMUNGUSone"
def transform(a):
chunks = []
for chunk in re.findall(r'[a-z]*[A-Z]*[a-z]*[ ]?', a):
if chunk:
if chunk[0].isupper():
chunk = chunk.capitalize()
chunks.append(chunk.title())
else:
substring = chunk[0].upper()+chunk[1:]
chunks.append(re.sub('[A-Z]+',lambda x:x.group().title(),substring))
return ''.join(chunks)
transform(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.