所以我有一个名字列表:
names = ['pete','carl','michael','steve']
现在我只打印每个名字的第二个字母,最后是(每个字母在彼此之下):
e
a
i
t
另外,我还有第二个问题。我想取代一个普通的' l'有一个资本' L'并将名称打印为(也是彼此之下的每个名称):
pete
carL
michaeL
steve
我希望有人知道怎么做:)提前谢谢!
答案 0 :(得分:1)
您的问题有一个非常简单的解决方案:
names = ['pete', 'carl', 'michael', 'steve']
def getSecondLetter(list):
for string in list:
if len(string) > 1:
print(string[1])
def capitalizeLetterL(list):
for string in list:
print(string.replace("l", "L"))
capitalizeLetterL(names)
getSecondLetter(names)
现在,您可以在程序中的任何位置使用它,将列表作为参数。
capitalizeLetterL()
和getSecondLetter()
,这有助于我们实现预期目标getSecondLetter()
内部,我使用for-in loop从列表中获取每个字符串并返回第二个字符,方法是使用string[1]
下标,返回第二个字符,因为索引在字符串从0
l
替换为L
根据OP的要求,我添加了一个仅使用while循环的版本:
names = ['pete', 'carl', 'michael', 'steve']
def getSecondLetter(list):
i=0
while i < len(list):
string=list[i]
if len(string) > 1:
print(string[1])
i+=1
def capitalizeLetterL(list):
i = 0
while i < len(list):
string = list[i]
print(string.replace("l", "L"))
i+=1
capitalizeLetterL(names)
getSecondLetter(names)
答案 1 :(得分:1)
您还可以使用列表推导
names = ['pete','carl','michael','steve']
for n in names:
if len(n) > 1:
print n[1]
uppercaseLNames = [''.join([x.upper() if x == 'l' else x for x in n]) for n in names]
for n in uppercaseLNames:
print n
输出
e
a
i
t
pete
carL
michaeL
steve
答案 2 :(得分:0)
打印(水果)
['mango', 'apple', ' grapes']
打印(水果[1] [1])
p