交换字符串中的案例

时间:2017-05-19 06:46:54

标签: python string python-3.x

我试图解决this challenge in hackerrank,要求将所有小写字母转换为大写字母,反之亦然。

我尝试使用以下代码:

def swap_case(s):
    length = len(s)
    i=0
    while length:
        if s1[i].isupper():
            s[i].lower()
        elif s[i].islower():
            s[i].upper()
        length-=1
        i+=1
    return s

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

但是返回的字符串与传递给函数的字符串相同。错误在哪里?

11 个答案:

答案 0 :(得分:1)

如评论及其他答案所述,字符串是不可变的。

请尝试以下操作:

s = input("Enter input: ")


def convert(ss):
    # Convert it into list and then change it
    newSS = list(ss)
    for i,c in enumerate(newSS):
        newSS[i] = c.upper() if c.islower() else c.lower()
    # Convert list back to string
    return ''.join(newSS)

print(s)
print(convert(s))

# Or use string build in method
print (s.swapcase())

答案 1 :(得分:1)

内置的str.swapcase已经这样做了。

def swap_case(s):
    return s.swapcase()

答案 2 :(得分:1)

def swap_case(s):
    new = ""
    for i in range(len(s)):
        if str.isupper(s[i]):
            new = new + str.lower(s[i])

        elif str.islower(s[i]):
            new = new + str.upper(s[i])

        else:
            new = new + str(s[i])
        
    return (new)

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

答案 3 :(得分:0)

正如@Julien在评论中所述upperlower方法返回一个副本,并且不会更改对象本身。请参阅this docs

编辑 @aryamccarthy让我想起了python中这类任务的现有功能:swapcase()方法。查看更多here。请注意,这也会返回字符串的副本。

答案 4 :(得分:0)

尝试一下

def swap_case(s):
    l =[]
    str1 = ''
    for i in s:
        if i.isupper():

            l.append(i.lower())
        elif i.islower():
            l.append(i.upper())
        else:
            l.append(i)
    return (str1.join(l))
if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

答案 5 :(得分:0)

Python-3内置的swapcase函数。

then()

输入:

const verifyEmp = async function () {
    return 'Verified';
}

const Employee = {
    async find() {
        return "An employee"
    }
}

Employee.find()
.then(emp => verifyEmp().then(msg => [emp, msg]))
.then(([emp, msg]) => {
    /* do something with amp and msg */
    console.log({emp: emp, verificationMsg: msg });
})
.catch((err) => {
    console.log(err);
})

输出:

def swap_case(s):
    return s.swapcase()

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

答案 6 :(得分:0)

def swap_case(s):
    return s.swapcase()

#or you can use list comprehension 

def swap_case(s):
    new=[ch.lower() if ch.isupper() else ch.upper() for ch in s]
    new=''.join(new)
    return new

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

答案 7 :(得分:0)

case "reset":
    if (!message.member.nickname) return message.channel.send("You don't have any nickname set.");
    message.member.setNickname("").then(member => {
        message.channel.send("Your nickname has been reset.");
    }).catch(e => {
        console.log(e);
        message.channel.send("Couldn't reset your nickname.");
    })

答案 8 :(得分:0)

def swap_case(s):
    a=" "
    for i in s:
        if i==i.lower():
            a=a+(i.upper())
        else:
            a=a+(i.lower())
    return (a)

答案 9 :(得分:0)

import string

upalf = string.ascii_uppercase

lowalf = string.ascii_lowercase

def swap_case(s):
    new = ""
    for i in s:
        if i in upalf:
            new += i.lower()
        elif i in lowalf:
            new += i.upper()
        else:
            new += i
    return new

if __name__ == '__main__':
    s = input()
    result = swap_case(s)
    print(result)

**在这个问题中,我使用了名为“string”的模块,里面有大写字母和小写字母的属性**

答案 10 :(得分:-1)

def swap_case(s):
    list_s= list(s)
    for index,char in enumerate(list_s):
        if char == char.lower():
            list_s[index] =char.upper()
        else:
            list_s[index]= char.lower()
            s = ''.join(list_s)
    return s

string = 'HackerRank.com presents "Pythonist 2".'
print(swap_case(string))