Python字符串拼接(包含字符串拼接数字)
在 Python 中拼接(连接)字符串很简单,可以直接将两个字符串紧挨着写在一起,具体格式为:
strname = "str1" "str2"
strname 表示拼接以后的字符串变量名,str1 和 str2 是要拼接的字符串内容。使用这种写法,Python 会自动将两个字符串拼接在一起。【示例】以连续书写的形式拼接字符串:
str1 = "Python教程" "http://c.biancheng网站站点" rel="nofollow" />
当然,Python教程http://c.biancheng网站站点" rel="nofollow" /> strname = str1 + str2
+
运算符也能拼接字符串常量。
【示例】使用+
运算符拼接字符串:name = "C++教程"
url = "http://c.biancheng网站站点" rel="nofollow" />
C++教程的网址是:http://c.biancheng网站站点" rel="nofollow" />
obj 表示要转换的对象,它可以是数字、列表、元组、字典等多种类型的数据。str(obj) repr(obj)
请看下面的代码:
name = "C语言中文网"
age = 8
course = 30
info = name + "已经" + str(age) + "岁了,共发布了" + repr(course) + "套教程。"
print(info)
运行结果:
C语言中文网已经8岁了,共发布了30套教程。
str() 和 repr() 的区别
str() 和 repr() 函数虽然都可以将数字转换成字符串,但它们之间是有区别的:
str() 用于将数据转换成适人类阅读的字符串形式。
repr() 用于将数据转换成适解释器阅读的字符串形式(Python 表达式的形式),适在开发和调试阶段使用;如果没有等价的语法,则会发生 SyntaxError 异常。
请看下面的例子:
s = "http://c.biancheng网站站点" rel="nofollow" />
<class 'str'>
http://c.biancheng网站站点" rel="nofollow" />