【问题标题】:How to change the case of the last letter in a string in python?如何在python中更改字符串中最后一个字母的大小写?
【发布时间】:2013-09-05 08:04:03
【问题描述】:

所以我想将字符串中的最后一个字符更改为小写。下面的代码是我用来向后打印字符串的方法,但是 list 将最后一个字符作为大写字母,我不知道如何解决这个问题!

        if s[-1] == "x":
            new = ""
            last_index = len(s)-1
            for i in range(last_index, -1, -1):
                new += s[i]
            s = new
            s = "".join(word[0].upper() + word[1:] for word in s.split())
        print (s)

例如: 输入是:

Inbox

这个输出:

XobnI

但我希望它输出:

Xobni

提前致谢!

【问题讨论】:

    标签: python string lowercase


    【解决方案1】:

    使用str.title:

    >>> "Inbox"[::-1].title()
    'Xobni'
    

    【讨论】:

    • 而且,一举一动,您不仅解决了特定问题,而且将整个事情所需的代码减少了大约90%。 +1,但只是因为我不能 +5 :-)
    猜你喜欢
    • 2012-01-03
    • 2011-05-12
    • 2021-01-06
    • 1970-01-01
    • 2021-12-17
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2011-12-11
    相关资源
    最近更新 更多