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

举报
ruochen 发表于 2021/03/28 01:15:13 2021/03/28
【摘要】 字符串与字符串之间连接字符串与非字符串之间连接输出对象特定数据 字符串与字符串之间连接 # 字符串与字符串之间连接的方式有5 种 ## 1:+(加号) s1 = 'hello' s2 = 'world' s = s1 + s2 print(s) 123456 helloworld helloworld 用逗号连接: hello world 格式化...

字符串与字符串之间连接

# 字符串与字符串之间连接的方式有5 种
## 1:+(加号)
s1 = 'hello'
s2 = 'world'
s = s1 + s2
print(s)

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
helloworld
helloworld
用逗号连接: hello world

格式化: <hello> <world>
join连接: hello world

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
## 2: 直接连接
s = 'hello''world'
print(s)

  
 
  • 1
  • 2
  • 3
helloworld

  
 
  • 1
## 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)

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
用逗号连接: hello world

  
 
  • 1
## 4: 格式化
s = '<%s> <%s>' % (s1, s2)
print('格式化:', s)

  
 
  • 1
  • 2
  • 3
格式化: <hello> <world>

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

  
 
  • 1
  • 2
  • 3
join连接: hello world

  
 
  • 1

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

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

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))

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
hello20
hello2012.44True

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

  
 
  • 1
  • 2
  • 3
格式化: <hello> <20> <12.44>

  
 
  • 1
## 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)

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
用逗号连接: hello*True*20*12.44

  
 
  • 1

输出对象特定数据

s1 = 'hello'
class MyClass: def __str__(self): return 'This is a MyClass Instance.'


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

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
helloThis is a MyClass Instance.

  
 
  • 1


4 - 进制之间的转换

文章来源: ruochen.blog.csdn.net,作者:若尘,版权归原作者所有,如需转载,请联系作者。

原文链接:ruochen.blog.csdn.net/article/details/104163761

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。