zoukankan      html  css  js  c++  java
  • 在Python中,我们经常会遇到字符串的拼接问题,在这里我总结了四种字符串的拼接方式

     1.使用%进行拼接

    如下

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

    job = input("Please input your job: ")
    sex = input("Please input your sex: ")
     

    information = '''

    ----------information %s --------------

    Name:%s

    Age:%s

    Job:%s

    Sex:%s

    '''%(name, name, age, job, sex)
    print(information)

    输出结果如下:


    ----------information li --------------

    Name:li

    Age:22

    Job:it

    Sex:nan

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

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

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

    job = input("Please input your job: ")
    sex = input("Please input your sex: ")

    information = '''

    ----------information '''+name +''' --------------

    Name:'''+name +'''

    Age:'''+age+'''

    Job:'''+job +'''

    Sex:'''+sex +'''

    '''
    print(information)

    输出结果如下:


    ----------information li --------------

    Name:li

    Age:22

    Job:it

    Sex:nan

    3.使用字典类型进行拼接

    name = input("Please input your name: ")
    age = input("Please input your age: ")
    job = input("Please input your job: ")
    sex = input("Please input your sex: ")
    information = '''

    ----------information {0} --------------

    Name:{0}

    Age:{1}

    Job:{2}

    Sex:{3}

    '''.format(name, age, job, sex)
    print(information)
    输出结果如下:

    ----------information li --------------

    Name:li

    Age:24

    Job:it

    Sex:nan

     4.赋值法拼接

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

    information = '''

    ----------information {_name} --------------

    Name:{_name}

    Age:{_age}

    Job:{_job}

    Sex:{_sex}

    '''.format(_name=name, _age=age, _job=job, _sex=sex)
    print(information)
    输出结果如下:

    ----------information li --------------

    Name:li

    Age:24

    Job:it

    Sex:nan

  • 相关阅读:
    1.shell编程-变量的高级用法
    1.python简介
    1.numpy的用法
    1.MySQL(一)
    1.HTML
    1.Go-copy函数、sort排序、双向链表、list操作和双向循环链表
    1.Flask URL和视图
    1.Django自学课堂
    1.Django安装与运行
    ajax跨站请求伪造
  • 原文地址:https://www.cnblogs.com/boosli/p/10019670.html
Copyright © 2011-2022 走看看