【问题标题】:Another alternating-case in-a-string in Python 3.+Python 3.+ 中的另一个交替大小写字符串
【发布时间】:2017-03-21 22:09:10
【问题描述】:

我对 Python 非常陌生,正在尝试了解如何操作字符串。

我想要做的是通过删除空格并将大小写从上到下交替来更改字符串,即“这比我想象的要难”到“ThIsIsHaRdErThAnItHoUgHtItWoUlDbE”

我拼凑了一个代码来删除空格(从这里大量借用):

string1 = input("Ask user for something.")
nospace = ""
for a in string1:
      if a == " ":
         pass
      else:
         nospace=nospace+a

...但就是无法理解大写/小写部分。这个网站上有几个类似的问题,我尝试修改其中的一些,但没有任何乐趣。我意识到我需要定义一个范围并遍历它,但这就是我画一个空白的地方。

for c in nospace[::]:
    d = ""
    c = nospace[:1].lower()
    d = d + c
    c = nospace[:1].upper
print d

我得到的只是一列 V。我显然弄错了。请问有人可以建议在哪里吗?提前致谢。

【问题讨论】:

    标签: python loops case uppercase lowercase


    【解决方案1】:

    这是一个可爱的方式来做到这一点:

    >>> s = "This is harder than I thought it would be"
    >>> from itertools import cycle
    >>> funcs = cycle([str.upper, str.lower])
    >>> ''.join(next(funcs)(c) for c in s if c != ' ')
    'ThIsIsHaRdErThAnItHoUgHtItWoUlDbE'
    >>>
    

    或者,正如 Moses 在 cmets 中所建议的那样,您可以使用 str.isspace,它不仅可以处理单个空格 ' '

    >>> ''.join(next(funcs)(c) for c in s if not c.isspace())
    'ThIsIsHaRdErThAnItHoUgHtItWoUlDbE'
    

    这种方法只对字符串进行一次传递。不过,两次通过的方法可能就足够了。

    现在,如果您从 nospace 字符串开始,最好的方法是转换为一些可变类型(例如 list)并使用切片赋值表示法。它的效率有点低,因为它构建了中间数据结构,但是在 Python 中切片是快速,所以它的性能可能相当不错。你必须在最后''.join,把它带回一个字符串:

    >>> nospace
    'ThisisharderthanIthoughtitwouldbe'
    >>> nospace = list(nospace)
    >>> nospace[0::2] = map(str.upper, nospace[0::2])
    >>> nospace[1::2] = map(str.lower, nospace[1::2])
    >>> ''.join(nospace)
    'ThIsIsHaRdErThAnItHoUgHtItWoUlDbE'
    >>>
    

    【讨论】:

    • 你可以使用if not c.isspace(),这样会更快。
    • @MosesKoledoye 不错!这也适用于所有空白!
    【解决方案2】:

    您正试图一次完成所有事情。不。将您的程序分解为多个步骤。

    1. 读取字符串。
    2. 从字符串中删除空格(正如@A.Sherif 刚刚演示的here
    3. 逐个字符遍历字符串。如果字符位于奇数位置,则将其转换为大写。否则,转换为小写。

    【讨论】:

    • 一次性做事没有错 :) 特别是如果您利用 Python 漂亮、富有表现力和有效的迭代器构造。
    【解决方案3】:

    所以你的第二个循环是你打破它的地方,因为原始列表没有被缩短, c=nospace[:1] 抓住字符串的第一个字符,这是唯一打印的字符。所以解决方案如下。

    string1 = str(input("Ask user for something."))
    
    nospace = ''.join(string1.split(' '))
    
    for i in range(0, len(nospace)):
        if i % 2 == 0:
            print(nospace[i].upper(), end="")
        else:
            print(nospace[i].lower(), end="")
    

    还可以将 if/else 语句替换为 ternary opperator

    for i in range(0, len(nospace)):
        print(nospace[i].upper() if (i % 2 == 0) else nospace[i].lower(), end='')
    

    使用枚举作为评论的最终方式

    for i, c in enumerate(nospace):
        print(c.upper() if (i % 2 == 0) else c.lower(), end='')
    

    【讨论】:

    • 与其迭代range(0, len(something)),不如使用range(len(something))。如果您要使用索引 元素,您实际上只想枚举:for i, e in enumerate(something)
    • 我知道范围的事情,但既然他说 python 的新手,我想我不会跳过那个。但是不知道枚举位谢谢!
    猜你喜欢
    • 2016-12-11
    • 2021-08-14
    • 2011-03-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    相关资源
    最近更新 更多