这是我的代码,我在列表中的特定字母之前和之后尝试大写字母。将前后的任何字母都大写将每个"z"之前和之后的前一个和下一个字母大写。在首都。其他字母均为小写。包含该字母的所有城市将存储在一个列表中并返回。如果我能得到一些输入就太好了。另外,如果我需要改变代码完全请让我知道其他的方式。我是新的,任何输入将不胜感激。由于
lst = ['brazzaville', 'zagreb', 'vaduz']
lst2 = []
for wrd in lst:
newwrd = ''
for ltr in wrd:
if ltr in 'ua':
newwrd += ltr.capitalize()
else:
newwrd += ltr
lst2.append(newwrd)
print(lst2)
我一直收到这个:
['brAzzAville', 'zAgreb', 'vAdUz']
但是我需要这个:
['brAzzAville', 'zAgreb', 'vadUz']
以下策略包括遍历单词并将z的index-1和index+1处的字母(如果存在的话)替换为大写字母:
lst2 = []
for wrd in lst:
wrd = wrd.lower()
for idx, letter in enumerate(wrd):
if letter == 'z':
if idx-1 > 0 and wrd[idx - 1] != 'z':
wrd = wrd.replace(wrd[idx - 1], wrd[idx - 1].upper())
if idx+1 < len(wrd) and wrd[idx + 1] != 'z':
wrd = wrd.replace(wrd[idx + 1], wrd[idx + 1].upper())
if "z" in wrd:
lst2.append(wrd)
print(lst2)
#['brAzzAville', 'zAgreb', 'vadUz']
我认为这个代码给出了正确的答案,验证一次
def findOccurrences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
lst = ['brazzaville', 'zagreb', 'vaduz']
lst2 = []
result = []
for wrd in lst:
newwrd = ''
result = findOccurrences(wrd, 'z')
for i in range(len(wrd)):
if (i + 1 in result or i - 1 in result) and wrd[i] != 'z':
newwrd += wrd[i].capitalize()
else:
newwrd += wrd[i]
lst2.append(newwrd)
print(lst2)
字符串第n个字符大写
res = lambda test_str,N: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else ''
伪代码- 循环遍历列表并过滤列表中包含'z'的字符串
[check(i) for i in lst if 'z' in i]
- 对于列表中的每个项目:
- 查找索引并将前面的字符大写为'z'第一次出现而不旋转。
preind = list(i).index('z')-1 if list(i).index('z')-1>0 else None
k = res(stri,preind) if(preind) else i
- 查找索引并在不旋转的情况下将后面的字符大写到'z'的最后一个字符。
postind = i.rfind('z')+1 if i.rfind('z')+1<len(i) else None
stri = res(i,preind) if(preind) else stri
代码lst = ['brazzaville', 'zagreb', 'vaduz']
def check(i):
stri = ""
k = ""
i = i.lower()
# lambda expression to capitalise Nth character in a string
res = lambda test_str,N: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else ''
# find index of the preceeding character to 'z'
preind = list(i).index('z')-1 if list(i).index('z')-1>0 else None
# find index of the succeeding character to 'z'
postind = i.rfind('z')+1 if i.rfind('z')+1<len(i) else None
# capitalise preceeding character to 'z'
stri = res(i,preind) if(preind) else i
# capitalise succeeding character to 'z'
k = res(stri,postind) if(postind) else stri
# return the processed string
return k
print([check(i) for i in lst if 'z' in i ])
#output
['brAzzAville', 'zAgreb', 'vadUz']