Skip to main content
 首页 » 编程设计

python之如何在同一行上连接两个函数

2025年05月04日14oomusou

def headName(): 
    print (Name[0].upper()) 
def tailName(): 
    print (Name[1:].lower()) 
 
Name = input("Please enter a name ") 
headName() 
tailName() 

那是我的代码;我想知道如何连接 headName() 和 tailName(),以便它们位于同一行。谢谢

请您参考如下方法:

如果不重写函数,您将无法做到这一点。换行符由 print 添加。由于您在函数内部调用了 print,因此您在函数外部所做的任何事情都无法撤消已添加到内部的换行符。

更好的办法是让您的函数返回值,然后在外部进行打印:

def headName(): 
    return Name[0].upper() 
def tailName(): 
    return Name[1:].lower() 
 
Name = input("Please enter a name ") 
print(headName(), tailName(), sep="") 

顺便说一句,你正在做的事情也可以直接用 Name.title() 来完成。