【问题标题】:Print second letter of each character in a list and replace letter打印列表中每个字符的第二个字母并替换字母
【发布时间】:2017-08-10 21:04:07
【问题描述】:

所以我有一个名字列表:

names = ['pete','carl','michael','steve']

现在我只想打印每个名字的第二个字母,所以最后是(每个字母在彼此下面):

e
a
i
t

另外,我还有第二个问题。我想用大写的 'L' 替换常规的 'l' 并将名称打印为(以及每个名称下方的名称):

pete
carL
michaeL
steve

我希望有人知道怎么做 :) 提前谢谢你!

【问题讨论】:

  • 你试过什么?请参阅How to Ask
  • 欢迎来到 Stack Overflow!您似乎在要求某人为您编写一些代码。 Stack Overflow 是一个问答网站,而不是代码编写服务。请see here 学习如何写出有效的问题。此外,学习如何组合一个可靠的minimal reproducible example,以便您的问题得到社区的广泛接受和轻松回答。
  • print([name[1] for name in names]).
  • 如果我使用它,我不应该将每个名称都称为“名称”吗?我应该怎么做?或者程序是否理解“名称中的名称”?

标签: python list replace


【解决方案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)

现在,您可以在程序的任何地方使用它,将列表作为参数。


说明

  • 我声明了两个functionscapitalizeLetterL()getSecondLetter(),这有助于我们实现预期目标
  • getSecondLetter() 内部,我使用for-in loop 从列表中获取每个字符串并返回第二个字符,方法是用string[1] 下标,返回第二个字符,因为字符串中的索引从@987654329 开始@
  • 我使用了字符串的replace()函数,将l替换为L

编辑

根据 OP 的要求,我添加了一个仅使用 while-loops 的版本:

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)

【讨论】:

  • 哦,非常感谢,这可能对我有帮助!我只是想知道,您是否也知道是否可以使用 while 语句来回答这些问题?所以一个while循环?
  • @LB_99 我已经用 while-loop 版本编辑了答案!希望这会有所帮助!
【解决方案2】:

你也可以使用列表推导

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

【讨论】:

    【解决方案3】:

    打印(水果)

    ['mango', 'apple', ' grapes']
    

    打印(水果[1][1])

    p
    

    【讨论】:

    • 这没有回答问题。正确答案已被接受
    猜你喜欢
    • 2022-08-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 2022-12-11
    • 2022-11-04
    • 2019-05-05
    • 2021-05-11
    • 1970-01-01
    相关资源
    最近更新 更多