2024-09-28 01:25:01 发布
网友
我用python编写了这段代码来大写和打印任何字符串的前4个字符。但我得到的结果是:
A P P L
我需要的输出是:
APPL
我应该在这里做些什么改变呢?你知道吗
def capital(uinput): slice4 = uinput[:4] for i in slice4: j = ord(i) j = j - 32 k = chr(j) print k print capital("apple")
用upper()怎么样?你知道吗
upper()
>>> s = "apple" >>> s[:4] 'appl' >>> s[:4].upper() 'APPL'
谈到您编写的代码,您可以通过以下方式对其进行修改:
def capital(uinput): slice4 = uinput[:4] result = "" for i in slice4: j = ord(i) j = j - 32 k = chr(j) result += k print result
或者,相同但在一行中没有附加变量:
def capital(uinput): print "".join([chr(ord(i) - 32) for i in uinput[:4]])
用
upper()
怎么样?你知道吗谈到您编写的代码,您可以通过以下方式对其进行修改:
或者,相同但在一行中没有附加变量:
相关问题 更多 >
编程相关推荐