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

本文详细介绍了在Python中使用四种不同方法进行字符串拼接的技巧,包括使用%操作符、加号(+)、字典类型及赋值法,旨在帮助初学者掌握高效字符串处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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

 

转载于:https://www.cnblogs.com/boosli/p/10019670.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值