简体   繁体   English

在函数中使用空格和字符串时遇到麻烦

[英]Having trouble with whitespace and strings in a function

Prompt 提示

Turn a string into rollercoaster case. 将一根绳子变成过山车箱。 The first letter of the sentence is uppercase, the next lowercase, the next uppercase, and so on. 句子的第一个字母是大写,下一个小写,下一个大写,依此类推。

Code

with open('test.txt') as file:
    for line in file:
        words = line.split()
        for word in words:
            chars = list(word)
            for index, char in enumerate(chars):
                if index == 0:
                    print char.upper(),
                elif is_even(index):
                    print char.upper(),
                elif is_odd(index):
                    print char,

Input 输入

Sunshine makes me happy, on a cloudy day

Output 产量

S u N s H i N e M a K e S M e H a P p Y , O n A C l O u D y D a Y

This is my first attempt at this problem. 这是我第一次尝试解决此问题。 I can't think of any other way to do this other than to iterate by each letter. 除了迭代每个字母外,我别无选择。 When I do this though I'm just treating the entire sentence as a string and spewing out characters. 但是,当我执行此操作时,我只是将整个句子视为字符串并输出字符。

You can uppercase just every second letter with an extended slice, picking every second letter: 您可以每隔扩展字母使用第二个字母大写,然后选择第二个字母:

>>> sample = 'Sunshine makes me happy, on a cloudy day'
>>> sample[::2].upper()
'SNHN AE EHPY NACOD A'
>>> sample[1::2].lower()
'usiemksm ap,o  luydy'

Now all you need to do is put those together again: 现在,您需要做的就是再次将它们放在一起:

from itertools import izip_longest

result = ''.join([l 
    for pair in izip_longest(sample[::2].upper(), sample[1::2].lower(), fillvalue='') 
    for l in pair])

izip_longest() pairs up the uppercased and lowercased strings again, making sure that if there is an odd number of characters to pad out the series with an empty string. izip_longest()再次将大写和小写的字符串配对,请确保是否有奇数个字符用空字符串填充序列。

Demo: 演示:

>>> from itertools import izip_longest
>>> ''.join([l 
...     for pair in izip_longest(sample[::2].upper(), sample[1::2].lower(), fillvalue='') 
...     for l in pair])
'SuNsHiNe mAkEs mE HaPpY, oN A ClOuDy dAy'

Note that whitespace isn't ignored here; 注意这里空白不被忽略; the m of make is lowercased even though the e at the end of Sunshine is too. 即使“ Sunshine ”结尾处的e也是如此, makem还是小写。

If you need to vary the letters more precisely, you can make use of iteration still: 如果需要更精确地改变字母,则可以仍然使用迭代:

from itertools import cycle
from operator import methodcaller

methods = cycle((methodcaller('upper'), methodcaller('lower')))
result = ''.join([next(methods)(c) if c.isalpha() else c for c in sample])

Here itertools.cycle() lets us alternate between two operator.methodcaller() objects , which either upper or lowercase the argument passed in. We only advance to the next one (using next() ) when the character is a letter. 在这里, itertools.cycle()使我们可以在两个operator.methodcaller()对象之间进行切换,后者传入的参数为大写或小写。当字符为字母时,我们仅前进到下一个(使用next() )。

Demo: 演示:

>>> from itertools import cycle
>>> from operator import methodcaller
>>> methods = cycle((methodcaller('upper'), methodcaller('lower')))
>>> ''.join([next(methods)(c) if c.isalpha() else c for c in sample])
'SuNsHiNe MaKeS mE hApPy, On A cLoUdY dAy'

If it's whitespace giving you trouble, you should use isalpha() to test if a character is a letter or not. 如果空格给您带来麻烦,则应使用isalpha()测试字符是否为字母。

with open('test.txt') as file:
  for line in file:
    newstr = ""
    go_to_upper = True

    for c in line:
      if c.isalpha():
        if go_to_upper:
          newstr += c.upper()
        else:
          newstr += c.lower()
        go_to_upper = not go_to_upper
      else:
        newstr += c

  print newstr

Input: Sunshine makes me happy, on a cloudy day 输入: Sunshine makes me happy, on a cloudy day

Output: SuNsHiNe MaKeS mE hApPy, On A cLoUdY dAy 输出: SuNsHiNe MaKeS mE hApPy, On A cLoUdY dAy

You'll only flip back and forth (using the go_to_upper boolean) when the character in question is a letter of the alphabet. 仅当所讨论的字符是字母时,才来回翻转(使用go_to_upper布尔值)。 Otherwise, it's outputted normally. 否则,将正常输出。 Notice that MaKeS starts with a capital letter, though SuNsHiNe ends with a lowercase letter, even with the space in the way. 请注意, MaKeS以大写字母开头,虽然SuNsHiNe以小写字母结尾,即使在这样的空间。

Also, instead of printing immediately (which gives you the weird spacing) we're putting our characters in a new list, which we'll print out all at once later. 另外,我们不是立即打印(这给您一个怪异的间距),而是将字符放入一个新列表中,稍后我们将全部打印出来。

Try this code : 试试这个代码:

import re
i = 1
with open('test.txt') as file:
    for line in file:
        words = line.split()
        for word in words:
            chars = list(word)
            for index, char in enumerate(chars):
                if re.compile('[a-zA-Z]').search(char):
                    i+=1
                    if i%2 !=0:
                        print char.upper(),
                    else :
                        print char.lower(),

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

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