将字符串中的标题大写单词转换为小写单词
Convert titlecase words in the string to lowercase words
我想将字符串中所有首字母大写的单词 (以大写字符开头且其余字符为小写的单词) 转换为小写字符。例如,如果我的初始字符串是:
text = " ALL people ARE Great"
我希望我的结果字符串是:
"ALL people ARE great"
我尝试了以下但没有用
text = text.split()
for i in text:
if i in [word for word in a if not word.islower() and not word.isupper()]:
text[i]= text[i].lower()
我也查看了相关问题Check if string is upper, lower, or mixed case in Python.。我想遍历我的数据框以及满足此条件的每个单词。
您可以使用str.istitle()
来检查您的单词是否代表标题字符串,即单词的第一个字符是否为大写,其余字符是否为小写。
要获得您想要的结果,您需要:
- 使用
str.split()
将您的字符串转换为单词列表
- 使用
str.istitle()
和 str.lower()
进行您需要的转换(我正在使用 列表理解 用于迭代列表并生成所需格式的新单词列表)
- 使用
str.join()
将列表连接回字符串:
例如:
>>> text = " ALL people ARE Great"
>>> ' '.join([word.lower() if word.istitle() else word for word in text.split()])
'ALL people ARE great'
您可以定义 transform
函数
def transform(s):
if len(s) == 1 and s.isupper():
return s.lower()
if s[0].isupper() and s[1:].islower():
return s.lower()
return s
text = " ALL people ARE Great"
final_text = " ".join([transform(word) for word in text.split()])
我想将字符串中所有首字母大写的单词 (以大写字符开头且其余字符为小写的单词) 转换为小写字符。例如,如果我的初始字符串是:
text = " ALL people ARE Great"
我希望我的结果字符串是:
"ALL people ARE great"
我尝试了以下但没有用
text = text.split()
for i in text:
if i in [word for word in a if not word.islower() and not word.isupper()]:
text[i]= text[i].lower()
我也查看了相关问题Check if string is upper, lower, or mixed case in Python.。我想遍历我的数据框以及满足此条件的每个单词。
您可以使用str.istitle()
来检查您的单词是否代表标题字符串,即单词的第一个字符是否为大写,其余字符是否为小写。
要获得您想要的结果,您需要:
- 使用
str.split()
将您的字符串转换为单词列表
- 使用
str.istitle()
和str.lower()
进行您需要的转换(我正在使用 列表理解 用于迭代列表并生成所需格式的新单词列表) - 使用
str.join()
将列表连接回字符串:
例如:
>>> text = " ALL people ARE Great"
>>> ' '.join([word.lower() if word.istitle() else word for word in text.split()])
'ALL people ARE great'
您可以定义 transform
函数
def transform(s):
if len(s) == 1 and s.isupper():
return s.lower()
if s[0].isupper() and s[1:].islower():
return s.lower()
return s
text = " ALL people ARE Great"
final_text = " ".join([transform(word) for word in text.split()])