• 在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

  • 相关阅读:
    3.30 DOM操作
    3.29 js例题
    3.28 函数
    3.27 数组例题
    Web 条件查询、分页查
    web页面增、删、改
    JDBC事务、下拉框
    JSTL、断点、JavaEE、DBUTils连接池
    jsp、el表达式
    Session技术 、jsp页面
  • 原文地址:https://www.cnblogs.com/boosli/p/10019670.html
Copyright © 2020-2023  润新知