Python中字符串拼接的三种方式

在Python中,我们经常会遇到字符串的拼接问题,在这里我总结了三种字符串的拼接方式:

    1.使用加号(+)号进行拼接

    加号(+)号拼接是我第一次学习Python常用的方法,我们只需要把我们要加的拼接到一起就行了,不是变量的使用单引号或双引号括起来,是变量直接相加就可以,但是我们一定要注意的是,当有数字的时候一定要转化为字符串格式才能够相加,不然会报错。

name = input("Please input your name: ")
age = input("Please input your age: ")
sex = input("Please input your sex: ")

print("Information of " + name + ":" + "\n\tName:" + name + "\n\tAge:" + age + "\n\tSex:" + sex)

输出结果如下:

Information of Alex:
    Name:Alex
    Age:38
    Sex:girl

    字符串拼接直接进行相加就可以,比较容易理解,但是一定要记得,变量直接相加,不是变量就要用引号引起来,不然会出错,另外数字是要转换为字符串才能够进行相加的,这点一定要记住,不能把数字直接相加。

    2.使用%进行拼接

name = input("Please input your name: ")
age = input("Please input your age: ")
sex = input("Please input your sex: ")

print("Information of \n\tName:%s\n\tAge:%s\n\tSex:%s" %(name,age,sex))

输出结果如下:

Information of Alex:
    Name:Alex
    Age:38
    Sex:girl

    第二种方式是使用%号的方法,我们在后面把变量统一进行添加,这样避免了使用加号的情况,能够让代码更加简短,这种方式我也喜欢,简单方便,只要知道自己需要的是什么样的信息,在里面设置格式,然后把变量进行添加就可以了。

    3.使用单引号('''''')或者双引号("""""")的方式

name = input("Please input your name: ")
age = input("Please input your age: ")
sex = input("Please input your sex: ")

message = '''
Information of %s:
Name:%s
Age:%s
Sex:%s
'''%(name,name,age,sex)
print(message)

输出结果如下:

Information of Alex:
    Name:Alex
    Age:38
    Sex:girl

    使用单引号('''''')或者双引号("""""")的方式,这种方式也很方便,我们首先进行定义,把我们需要的格式进行定义,要经常尝试这几种格式的方法,这三种方式我都觉得挺好的。

posted @ 2017-04-14 21:11  (野生程序员)  阅读(132933)  评论(0编辑  收藏  举报