前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >3 - 各种变量与值之间的多种连接方式

3 - 各种变量与值之间的多种连接方式

原创
作者头像
ruochen
修改2021-05-22 17:16:14
7020
修改2021-05-22 17:16:14
举报

字符串与字符串之间连接

代码语言:txt
复制
# 字符串与字符串之间连接的方式有5 种
## 1:+(加号)
s1 = 'hello'
s2 = 'world'
s = s1 + s2
print(s)
代码语言:txt
复制
helloworld
代码语言:txt
复制
helloworld
代码语言:txt
复制
用逗号连接: hello world
代码语言:txt
复制
格式化: <hello> <world>
代码语言:txt
复制
join连接: hello world
代码语言:txt
复制
## 2: 直接连接
s = 'hello''world'
print(s)
代码语言:txt
复制
helloworld
代码语言:txt
复制
## 3: 用逗号(,)连接,标准输出的重定向
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print('hello', 'world')
# 恢复标准输出
sys.stdout = old_stdout
result_str = result.getvalue()
print('用逗号连接:', result_str)
代码语言:txt
复制
用逗号连接: hello world
代码语言:txt
复制
## 4: 格式化
s = '<%s> <%s>' % (s1, s2)
print('格式化:', s)
代码语言:txt
复制
格式化: <hello> <world>
代码语言:txt
复制
## 5: join
s = ' '.join([s1, s2])
print('join连接:', s)
代码语言:txt
复制
join连接: hello world

字符串与非字符串之间连接

代码语言:txt
复制
# 字符串与非字符串之间连接

s1 = 'hello'
s2 = 'world'

## 1:加号
n = 20
s = s1 + str(n)
print(s)
v = 12.44
b = True
print(s1 + str(n) + str(v) + str(b))
代码语言:txt
复制
hello20
代码语言:txt
复制
hello2012.44True
代码语言:txt
复制
## 2: 格式化
s = '<%s> <%d> <%.2f>' % (s1, n, v)
print('格式化:', s)
代码语言:txt
复制
格式化: <hello> <20> <12.44>
代码语言:txt
复制
## 3: 重定向
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print(s1, True, n, v, sep='*')
# 恢复标准输出
sys.stdout = old_stdout
result_str = result.getvalue()
print('用逗号连接:', result_str)
代码语言:txt
复制
用逗号连接: hello*True*20*12.44

输出对象特定数据

代码语言:txt
复制
s1 = 'hello'
class MyClass:
    def __str__(self):
        return 'This is a MyClass Instance.'


my = MyClass()
s = s1 + str(my)
print(s)
代码语言:txt
复制
helloThis is a MyClass Instance.

[

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 字符串与字符串之间连接
  • 字符串与非字符串之间连接
  • 输出对象特定数据
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档