定义字符串

时间:2015-09-23 19:06:02

标签: python string python-3.x

我如何在python中定义字符串?我有问题

def printName(x):
    msg = "Welcome to class, "
    print(msg, self.name)

printName(john)

在这种情况下,我试图找出我应该在函数" printName"之后放置的内容。并使它所以它调用的字符串(在这种情况下为john)将显示,并打印消息"欢迎来到课堂,约翰"

请注意我是初学者。

我想设置它,所以我输入shell

>>> printName(john)

它将返回"欢迎来到课堂,约翰"

显然,我可以使用一个非常简单的print()命令来完成这项工作,但是我需要知道如何使用定义的printName命令来完成它。我在3.3.5上使用Wing101

2 个答案:

答案 0 :(得分:3)

您可以轻松完成以下操作

def print_name(name):
    print("Welcome to class, {0}".format(name))

print_name("John")

就您自己的解决方案而言,我不知道您在做什么。

  1. 什么是self
  2. 应该是john而不是约翰
  3. 编辑问题

    def printName(x):
        msg = "Welcome to class, "
        print(msg + x) # '+' is concatenation symbol in python, no self variable exists here
    
    printName('john') # Since it's a string should be quoted
    

答案 1 :(得分:1)

看起来你正在寻找这样的东西:

def printName(name):
    msg = "Welcome to class, "
    print(msg, name)

person = 'John'
printName(person)

请注意,我将变量person分配给字符串' John',然后将该变量传递给该函数。该函数将参数接收到局部变量name中,并将该变量与消息一起打印。