1.3不同类型的变量或值首尾相接

学习目标:

①字符串与字符串连接

②字符串与非字符串连接

③字符串与对象连接时让对象输出特定内容

  • Python日常

内容展示:

①:字符串与字符串连接:

1.加号(+)

s1 = 'Hello'
s2 = 'World'
s = s1 + s2
print(s)  # Hello World

2.直接连接

s = 'Hello World
print(s)   # Hello World

3.逗号相连, 标准输出的重定向

from io import StringIO
import sys
old_stdout = sys.stdout  # 方便后续恢复标准输出
result = StringIO()
sys.stdout = result
print('Hello', 'World')
sys.stdout = old_stdout  # 恢复标准输出
reslut_str = result.getvalue()
print('用逗号连接: ', reslut_str)   # 用逗号连接:  Hello World

4.格式化

s1 = 'Hello'
s2 = 'World'
s = '<%s> <%s>' % (s1, s2)
print('格式化: ', s)

5.使用join

s = ''.join([s1, s2])
print('join连接:', s)

②:字符串与非字符串连接:

1.加号(+)

n = 20
s1 = 'Hello'
s = s1 + str(n)   # 使用str进行类型转换
print(s)  # Hello20

2.格式化

s1 = 'Hello'
n = 20
f = 24.24
s = '<%s> <%d> <%.2f>' %(s1, n, f)   # .2f  小数点后保留两位
print(s)   # <Hello> <20> <24.24>

3.重定向

from io import StringIO
import sys

s1 = 'Hello'
n = 20
f = 24.24
b = True
old_stdout = sys.stdout  # 方便后续恢复标准输出
result = StringIO()
sys.stdout = result
print(s1, b, n, f, sep='*')   #  sep定义输出间隔
sys.stdout = old_stdout  # 恢复标准输出
reslut_str = result.getvalue()
print('用逗号连接: ', reslut_str)  # 用逗号连接:  Hello*True*20*24.24

sep定义输出间隔


③字符串与对象连接时让对象输出特定内容

s1 = 'Hello '


class MyClass:
    def __str__(self):
        return 'I am Strong'   # return 为我们想要输出的内容

my = MyClass()
s = s1 + str(my)   # 使用str进行类型转换
print(s)  # Hello I am Strong

总结:

1.在字符串与非字符串或者对象连接时,注意类型的转换(str)
2.使用格式化连接的时,注意<%?> 要与后方数据类型对应


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿中在线啃码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值