繁体   English   中英

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

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

提示

将一根绳子变成过山车箱。 句子的第一个字母是大写,下一个小写,下一个大写,依此类推。

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,

输入

Sunshine makes me happy, on a cloudy day

产量

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

这是我第一次尝试解决此问题。 除了迭代每个字母外,我别无选择。 但是,当我执行此操作时,我只是将整个句子视为字符串并输出字符。

您可以每隔扩展字母使用第二个字母大写,然后选择第二个字母:

>>> 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'

现在,您需要做的就是再次将它们放在一起:

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()再次将大写和小写的字符串配对,请确保是否有奇数个字符用空字符串填充序列。

演示:

>>> 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'

注意这里空白不被忽略; 即使“ Sunshine ”结尾处的e也是如此, makem还是小写。

如果需要更精确地改变字母,则可以仍然使用迭代:

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])

在这里, itertools.cycle()使我们可以在两个operator.methodcaller()对象之间进行切换,后者传入的参数为大写或小写。当字符为字母时,我们仅前进到下一个(使用next() )。

演示:

>>> 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'

如果空格给您带来麻烦,则应使用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

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

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

仅当所讨论的字符是字母时,才来回翻转(使用go_to_upper布尔值)。 否则,将正常输出。 请注意, MaKeS以大写字母开头,虽然SuNsHiNe以小写字母结尾,即使在这样的空间。

另外,我们不是立即打印(这给您一个怪异的间距),而是将字符放入一个新列表中,稍后我们将全部打印出来。

试试这个代码:

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