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

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 = 'Let's 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()相同的值。

 

posted @ 2019-10-12 22:08  刀客王  阅读(198)  评论(0编辑  收藏  举报