字符串与字符串之间连接的方式有5种
1. 加号( + )
2. 直接连接(字符串类型的值,不能是变量)
s = "hello" "world"
print(s)
3. 逗号(,)连接
print('hello', 'world')
3. 输出重定位 (print函数)
1 2 3 4 5 6 7 8 9 10 11 12 | 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) hello world |
4. 格式化
5. join方法
s = " ".join([s1, s2])
字符串与非字符串之间如何连接
1:加号
1 2 3 4 5 6 7 | s1 = 'hello' n = 20 v = 12.44 b = True print (s1 + str (n) + str (v) + str (b)) hello2012. 44True |
2:格式化
1 2 3 4 5 6 7 | s = '%s%d%f' % (s1,n,v) print (s) s = '%s%d%.2f' % (s1,n,v) print (s) hello2012. 440000 hello2012. 44 |
3:重定向
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | s1 = 'hello' n = 20 v = 12.44 b = True from io import StringIO import sys old_stdout = sys.stdout result = StringIO() sys.stdout = result print (s1, n, v, b, sep = '') # 恢复标准输出 sys.stdout = old_stdout result_str = result.getvalue() print (result_str) hello2012. 44True |
字符串与类
1 2 3 4 5 6 7 8 9 10 11 | class MyClass: def __str__( self ): return 'This is a MyClass Instance.' my = MyClass() s1 = 'hello' s = s1 + str (my) print (s) helloThis is a MyClass Instance. |
标签:
Python 100讲
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!