首页 > 其他 > 详细

数据类型之字符串(string)(一)

时间:2019-10-12 23:28:23      阅读:128      评论:0      收藏:0      [点我收藏+]

1、引号括起的都是字符串(可以时空格),可以是‘‘(单引号)、“”(双引号)、‘‘‘‘‘‘(三引号)、""""""(我还是三引号)。

1 str = This is a string
2 str2 = "This is a string"
3 str3 = ‘‘‘This is a string‘‘‘
4 str4 = """This is a string"""     # 三引号用于需要分行的情况。

 2、10和"10"是不同的,前者是数字,后者是字符串。

3、常见错误:

srt = Lets go!
SyntaxError: invalid syntax
语法错误

解决方法:

1)用不同的引号包裹

str = "Let‘s go !"

2)使用转义符(\)

srt = Let\‘s go!

 4、字符串的拼接

"py" + "thon"

运行结果
python

  注意:不同的数据类型不能执行上述命令。需要对数据类型转换才能执行。

>>> a = 250
>>> b = "python"
>>> a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: int and str

解决方法

>>> repr(a) + b
250python

或者

>>> str(a) + b
250python

大多数情况下他们的效果相同

如:

>>> type(repr(a))
<class str>

>>> type(str(a))
<class str>


>>> str(a) == repr(a)
True

 

但是既然是不同的函数肯定有不同的地方

如:

>>> str(b)
python

>>> repr(b)
"‘python‘"

>>> str(b) == repr(b)
False

 

概括起来可以这样说str()会将对象转化为可读性较好的字符串,而repr()会将对象转化为供解释器读取形式的字符串。一个对象没有适于人阅读的解释形式的话,str()会返回与repr()相同的值。

 

数据类型之字符串(string)(一)

原文:https://www.cnblogs.com/doc-wang/p/11657696.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!