简体   繁体   English

如何使用if语句使for循环遍历字符串中的每个项目?

[英]How to make a for loop iterate through each item in a string with an if statement?

I'm trying to make a function that takes in a string from a user and then outputs the same string.我正在尝试创建一个函数,该函数从用户那里接收一个字符串,然后输出相同的字符串。 However for each letter in an even position it outputs the corresponding lower case letter, and for each letter in an odd position it outputs the corresponding uppercase letter.然而,对于偶数位置的每个字母,它输出相应的小写字母,对于奇数位置的每个字母,它输出相应的大写字母。 Keep in mind only one word will be passed through it at a time.请记住,一次只会传递一个单词。

I've tried to create a for loop with an if statement nested within it, but so far, the for loop stops after iterating through the first letter.我试图创建一个 for 循环,其中嵌套了一个 if 语句,但到目前为止,for 循环在遍历第一个字母后停止。 My code is below:我的代码如下:

def converter(string):
    for letters in string:
        if len(letters) % 2 == 0:
            return letters.lower()
        elif len(letters)% 2 != 0:
            return letters.upper()

When I run the code:当我运行代码时:
converter('app')转换器('应用程序')

The output I get is 'A'我得到的输出是'A'
The expected output should be 'aPp'预期的输出应该是“aPp”

The first thing you need to know is that in Python, strings are immutable.您需要知道的第一件事是,在 Python 中,字符串是不可变的。 So "modifying" a string means you have to build a new string from scratch in (here, I call that newstring ).所以“修改”一个字符串意味着你必须从头开始构建一个新的字符串(在这里,我称之为newstring )。

Second, you are misunderstanding the loop.其次,你误解了循环。 You are saying for letters in string .你说for letters in string This loop iterates over each letter of the string.此循环遍历字符串的每个字母。 On the first iteration, letters is the first letter of the strong.在第一次迭代中, letters是强的第一个字母。 You then convert it to upper case (since the length of a single letter is always 1), and return it.然后将其转换为大写(因为单个字母的长度始终为 1),然后返回。 You aren't reaching the rest of the letters!你没有到达其余的字母! In the code below, I change the plurality to just letter to make this idea clear.在下面的代码中,我将复数更改为仅letter以明确这个想法。

This amends all of those problems:这修正了所有这些问题:

def converter(string):
    newstring = ""
    for i, letter in enumerate(string):
        if i % 2 == 0:
            newstring += letter.lower()
        elif i % 2 != 0:
            newstring += letter.upper()
    return newstring

This can be boiled down to a nice list comprehension:这可以归结为一个很好的列表理解:

def converter(string):
    return "".join([letter.lower() if i % 2 == 0 else letter.upper()
                    for i, letter in enumerate(string)])
In [1]: def converter(string):
   ...:     return ''.join([j.upper() if i % 2 == 1 else j.lower() for i, j in enumerate(string)])


In [2]: converter('apple')
Out[2]: 'aPpLe'
''.join([s.lower() if c % 2 == 0 else s.upper() for c, s in enumerate('apple')])
# returns 'aPpLe'

first check for the condition, then iterate through the string using the nice old enumerate built-in.首先检查条件,然后使用内置的漂亮的旧enumerate遍历字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM