不同数类型的变量或值如何连接

'''
字符串与字符串之间如何连接,有几种方式
'''
#第1种 使用 + (加号)
s1 = 'hello'
s2 = 'world'
s = s1 + s2
print(s+'\n')

#第2种 直接连接
s = 'hello' 'world''\n'
print(s)

#第3种 使用逗号(,)连接,标准输出的重定向
print('hello','world','\n')
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print('hello','world')
sys.stdout = old_stdout
print('用逗号连接:',result.getvalue())

#第4种 格式化 %
s = '<%s> <%s>\n'%(s1,s2)
print(s)

#第5种 join
s = ' '.join([s1,s2])
print('join连接:',s,'\n\n\n')

'''
字符串与非字符串之间如何连接
'''
#1:加号+
n = 20
b = True
print(s1 + str(n) + str(b) + '\n')

#2:格式化%
s = '<%s> <%d> <%.2f>\n'%(s1,n,1.235)
print(s)

#3:重定向
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print(s1,n,b,sep='**')
sys.stdout = old_stdout
print('重定向:',result.getvalue(),'\n\n')


'''
字符串与对象连接如何让对象输出特定内容
'''

class MyClass():
    def __str__(self):
        return ' This is a MyClass instance'

my = MyClass()
print(s1 + str(my))

The result:

helloworld

helloworld

hello world

用逗号连接: hello world

join连接: hello world

hello20True

<20> <1.24>

重定向: hello20True

hello This is a MyClass instance

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值