我需要一个可以执行以下操作的python函数:
给出输入' t'并且' tattle'它应该返回如下列表: ['闲话''闲话''闲话'] 或者使用' z'和' zzzzz': [' ZZZZZ'' ZZZZZ'' ZZZZZ'' ZZZZZ'' ZZZZZ']
我对以下内容进行了编码,但它不适用于第二个示例,因为当前函数会检查basestr是否与结果列表R中已有的匹配,并且由于具有多个basetr&的单词而可以获取误报#39;已经在这个词中了。有人有什么建议吗?
def all_variants(wrapletter,word):
L,R,WLU,basestr=list(word),[],wrapletter.upper(),''
if L.count(wrapletter)==1:
for char in L:
if wrapletter==char:
basestr=basestr+WLU
else:
basestr=basestr+char
R.append(basestr)
return(R)
else:
for i in range(L.count(wrapletter)):
basestr=''
if i==0 and L[0]==wrapletter:
basestr=WLU
for char in range(1,len(L)):
basestr=basestr+L[char]
R.append(basestr)
else:
for char in L:
if wrapletter==char:
if WLU in basestr:
basestr=basestr+char
elif basestr in str(R):
basestr=basestr+char
else:
basestr=basestr+WLU
else:
basestr=basestr+char
R.append(basestr)
R.remove(R[0])
return(R)
答案 0 :(得分:1)
它不优雅,但也许这就是你需要的东西?
target = "daaddaad"
def capitalize(target_letter, word):
return [word[:i] + word[i].upper() + word[i + 1:]
for i in xrange(len(word)) if word[i] == target_letter]
print capitalize("d", target)
输出:
['Daaddaad', 'daaDdaad', 'daadDaad', 'daaddaaD']
答案 1 :(得分:1)
def all_variants(wrapletter, word):
list = []
for i in range(len(word)):
if(word[i]==wrapletter):
start = word[0:i].lower()
str = word[i].upper()
end = word[i+1::].lower()
list.append(start+str+end)
return list
运行此功能时返回:
>>>all_variants("t", "tattle")
['Tattle', 'taTtle', 'tatTle']
>>>all_variants("z", "zzzzz")
['Zzzzz', 'zZzzz', 'zzZzz', 'zzzZz', 'zzzzZ']
答案 2 :(得分:1)
inp = 't'
word = 'tattle'
inds = (i for i,ele in enumerate(word) if ele == inp)
print([word[:i]+word[i].upper()+word[i+1:] for i in inds])
['Tattle', 'taTtle', 'tatTle']
答案 3 :(得分:1)
试试这个。我遍历每个字母,将其移至大写,并将其与原始字符串的其他部分夹在一起。
def all_variants(wrapletter, word):
variants = []
for i, letter in enumerate(word):
if letter == wrapletter:
variants.append(word[:i] + letter.upper() + word[i+1:])
return variants
print all_variants('z', 'zzzzz')
print all_variants('t', 'tattle')