Python替代案例

时间:2017-08-31 04:15:41

标签: python

我想在python中使用备用案例打印一个字符串。例如,我的字符串是" Python " 。我想打印它像" PyThOn " 。我怎么能这样做?

7 个答案:

答案 0 :(得分:1)

您可以试用spongemock库!

或者,如果您想要将所有其他字母大写,请查看此question

答案 1 :(得分:1)

mystring="Python"
newstring=""
odd=True
for c in mystring:
  if odd:
    newstring = newstring + c.upper()
  else:
    newstring = newstring + c.lower()
  odd = not odd
print newstring

答案 2 :(得分:0)

试一试:

def upper(word, n):
    word = list(word)
    for i in range(0, len(word), n):
        word[i] = word[i].upper()
    return ''.join(word)

答案 3 :(得分:0)

您可以使用列表理解进行迭代,并根据每个字符的偶数或奇数强制大小写。

示例:

s = "This is a test string"
ss = ''.join([x.lower() if i%2 else x.upper() for i,x in enumerate(s)])
print ss

s = "ThisIsATestStringWithoutSpaces"
ss = ''.join([x.lower() if i%2 else x.upper() for i,x in enumerate(s)])
print ss

输出:

 ~/so_test $ python so_test.py 
ThIs iS A TeSt sTrInG
ThIsIsAtEsTsTrInGwItHoUtSpAcEs
 ~/so_test $

答案 4 :(得分:0)

对于随机大写和小字符

>>> def test(x):
...    return [(str(s).lower(),str(s).upper())[randint(0,1)] for s in x]
... 
>>> print test("Python")
['P', 'Y', 't', 'h', 'o', 'n']
>>> print test("Python")
['P', 'y', 'T', 'h', 'O', 'n']
>>> 
>>> 
>>> print ''.join(test("Python"))
pYthOn
>>> print ''.join(test("Python"))
PytHon
>>> print ''.join(test("Python"))
PYTHOn
>>> print ''.join(test("Python"))
PytHOn
>>> 

您的问题代码是:

st = "Python"

out = ""
for i,x in enumerate(st):
    if (i%2 == 0):
        out += st[i].upper()
    else:
        out += st[i].lower()
print out

答案 5 :(得分:0)

如果你不能以某种方式在那里工作zip(),那就不是Pythonic了:

string = 'Pythonic'

print(''.join(x + y for x, y in zip(string[0::2].upper(), string[1::2].lower())))

<强>输出

PyThOnIc

答案 6 :(得分:-1)

string = input ("Entre string: ")
  

  

s = ""
for i in range(len(string)):
    if not i % 2 :
       s = s + string[i].upper()
    else:
       res = s + string[i].lower()
  
print(s)