如何将一行中的输出作为字符串获取?

2024-09-28 01:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我用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")

Tags: 字符串代码inapplefordefprint大写
1条回答
网友
1楼 · 发布于 2024-09-28 01:25:01

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

相关问题 更多 >

    热门问题