Python 交换字符串中的大写和小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36247173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:37:30  来源:igfitidea点击:

Swapping uppercase and lowercase in a string

pythonstringpython-2.xuppercaselowercase

提问by Marco G. de Pinto

I would like to change the chars of a string from lowercase to uppercase.

我想将字符串的字符从小写更改为大写。

My code is below, the output I get with my code is a; could you please tell me where I am wrong and explain why? Thanks in advance

我的代码在下面,我的代码得到的输出是a;你能告诉我我错在哪里并解释原因吗?提前致谢

test = "AltERNating"

def to_alternating_case(string):
    words = list(string)
    for word in words:
        if word.isupper() == True:
            return word.lower()
        else:
            return word.upper()  

print to_alternating_case(test)

回答by folkol

If you want to invert the case of that string, try this:

如果要反转该字符串的大小写,请尝试以下操作:

>>> 'AltERNating'.swapcase()
'aLTernATING'

回答by Amit Gold

There are two answers to this: an easy one and a hard one.

对此有两个答案:一个简单的和一个困难的。

The easy one

最简单的

Python has a built in function to do that, i dont exactly remember what it is, but something along the lines of

Python 有一个内置函数可以做到这一点,我不完全记得它是什么,但是类似

string.swapcase()

The hard one

最难的

You define your own function. The way you made your function is wrong, because iterating over a string will return it letter by letter, and you just return the first letter instead of continuing the iteration.

您定义自己的函数。你制作函数的方式是错误的,因为迭代一个字符串会一个字母一个字母地返回它,你只返回第一个字母而不是继续迭代。

def to_alternating_case(string):
    temp = ""
    for character in string:
        if character.isupper() == True:
            temp += character.lower()
        else:
            temp += word.upper()
    return temp

回答by hemraj

You are returning the first alphabet after looping over the word alternating which is not what you are expecting. There are some suggestions to directly loop over the string rather than converting it to a list, and expression if <variable-name> == Truecan be directly simplified to if <variable-name>. Answer with modifications as follows:

您在循环交替单词后返回第一个字母,这不是您所期望的。有一些建议是直接循环遍历字符串而不是将其转换为列表,并且表达式if <variable-name> == True可以直接简化为if <variable-name>. 回答修改如下:

test = "AltERNating"

def to_alternating_case(string):
    result = ''
    for word in string:
        if word.isupper():
            result += word.lower()
        else:
            result += word.upper()
    return result

print to_alternating_case(test)

OR using list comprehension :

或使用列表理解:

def to_alternating_case(string):
    result =[word.lower() if word.isupper() else word.upper() for word in string]
    return ''.join(result)

OR using map, lambda:

或使用地图,lambda:

def to_alternating_case(string):
    result = map(lambda word:word.lower() if word.isupper() else word.upper(), string)
    return ''.join(result)

回答by Billal Begueradj

That's because your function returns the first character only. I mean returnkeyword breaks your forloop.

那是因为您的函数只返回第一个字符。我的意思是return关键字打破了你的for循环。

Also, note that is unnecessary to convert the string into a list by running words = list(string)because you can iterate over a stringjust as you did with the list.

另请注意,没有必要通过运行将字符串转换为列表,words = list(string)因为您可以像处理列表一样遍历字符串

If you're looking for an algorithmic solution instead of the swapcase()then modify your method this way instead:

如果您正在寻找算法解决方案而不是swapcase()然后以这种方式修改您的方法:

test = "AltERNating"

def to_alternating_case(string):
    res = ""
    for word in string:
        if word.isupper() == True:
            res = res + word.lower()
        else:
            res = res + word.upper()
    return res


print to_alternating_case(test)

回答by schwobaseggl

Your loop iterates over the characters in the input string. It then returns from the very first iteration. Thus, you always get a 1-char return value.

您的循环遍历输入字符串中的字符。然后它从第一次迭代返回。因此,您总是会得到一个 1-char 的返回值。

test = "AltERNating"

def to_alternating_case(string):
    words = list(string)
    rval = ''
    for c in words:
        if word.isupper():
            rval += c.lower()
        else:
            rval += c.upper()
    return rval    

print to_alternating_case(test)

回答by Leo Leontev

You should do that like this:

你应该这样做:

test = "AltERNating"

def to_alternating_case(string):
    words = list(string)
    newstring = ""
        if word.isupper():
            newstring += word.lower()
        else:
            newstring += word.upper()  
    return alternative
print to_alternating_case(test)

回答by Krishna Kanth

def myfunc(string):
    i=0
    newstring=''
    for x in string:
        if i%2==0: 
            newstring=newstring+x.lower()
        else:
            newstring=newstring+x.upper()
        i+=1
    return newstring

回答by Rakesh Sharma

contents='abcdefgasdfadfasdf'
temp=''
ss=list(contents)
for item in range(len(ss)):
    if item%2==0:
        temp+=ss[item].lower()
    else:
        temp+=ss[item].upper()

print(temp)

you can add this code inside a function also and in place of print use the return key

您也可以在函数中添加此代码,并使用返回键代替打印

回答by dev prakash pandey

string=input("enter string:")
temp=''
ss=list(string)
for item in range(len(ss)):
    if item%2==0:
        temp+=ss[item].lower()
    else:
        temp+=ss[item].upper()
print(temp)

回答by Phidelux

Here is a short form of the hard way:

这是困难方式的简短形式:

alt_case = lambda s : ''.join([c.upper() if c.islower() else c.lower() for c in s])
print(alt_case('AltERNating'))

As I was looking for a solution making a all upper or all lower string alternating case, here is a solution to this problem:

由于我正在寻找一种解决方案,使全上或全下弦交替情况,这里是这个问题的解决方案:

alt_case = lambda s : ''.join([c.upper() if i%2 == 0 else c.lower() for i, c in enumerate(s)])
print(alt_case('alternating'))