Python 根据条件替换列表中的字符

Python 根据条件替换列表中的字符,python,list,Python,List,基于某些条件,我正在尝试替换列表中的字符 tmp = ['T', 'h', 'e', '/', ' * ', 's', 'k', 'y', ' * ', 'i', 's', '/', '/', 'b', 'l', 'u', 'e'] tmp_string = "".join(tmp) result = re.sub(r'[\*|/]{2}', ' ', tmp_string) result = result.title().replace('*', ' ').replace('/', ' ').

基于某些条件,我正在尝试替换列表中的字符

tmp = ['T', 'h', 'e', '/', ' * ', 's', 'k', 'y', ' * ', 'i', 's', '/', '/', 'b', 'l', 'u', 'e']
tmp_string = "".join(tmp)
result = re.sub(r'[\*|/]{2}', ' ', tmp_string)
result = result.title().replace('*', ' ').replace('/', ' ').replace('  ', ' ')
我想对代码做一点修改,因为它与我的预期输出不匹配

  • 预期:天空是蓝色的
  • 我的输出:天空是蓝色的

我不希望“is”的“I”大写。

您可以使用带有三元表达式的生成器来检查字符是否为字母数字:

重新导入
l=['T'、'h'、'e'、'/'、'*'、's'、'k'、'y'、'*'、'i'、's'、'/'、'/'、'b'、'l'、'u'、'e']
tmp=”“.join(char if char.isalpha()else''表示l中的字符)
#这将在*和/所在的位置放置空格
#然后使用正则表达式压缩空格
mystr=re.sub('\s{2,}','',tmp)
打印(mystr)
输出:天空是蓝色的

然后,要获得所需的输出:

chars=[]
not_capitalize=set(['is',and'])#您可以在这里输入其他不想大写的单词
#“拆分”将创建在空格上拆分的单词数组
对于mystr.split()中的字符:
如果字符不大写:
chars.append(char)
持续
#把第一个字母和单词的其余部分分开
第一个字母,rest=char[0],char[1:]
#将大写的第一个字母与单词的其余部分缝合在一起
chars.append(“%s%s”%(第一个字母.upper(),rest))
#加入并打印
打印(''.join(chars))
#天空是蓝色的

问题在于
title()
将字符串的第一个字符大写。IUCC一个简单的例子会让你走。使用带有条件的
title()

' '.join([i.title() if i not in ['is','and'] else i for i in 'the sky is blue'.split()])
试试这个

import re
tmp=['T', 'h', 'e', '/', ' * ', 's', 'k', 'y', ' * ', 'i', 's', '/', '/', 'b', 'l', 'u', 'e']

misc_words = ('is', 'the')

tmp_string = "".join(tmp)
result = re.sub(r'[\*|/]', ' ', tmp_string)
result = re.sub(r' +', ' ', result) # replace one or more consecutive spaces with a single space
#result = result.title().replace('*', ' ').replace('/', ' ').replace('  ', ' ') # this is done by fixng the first regex
words = result.split()
new_words = []
for word in words:
    if word not in misc_words:
        new_words.append(word[0].upper() + word[1:])
    else:
        new_words.append(word)

print(new_words)

这里的
tmp
是什么?您调用了
title()
,它将单词的首字母大写。如果您不想这样做,请不要调用
title()