1、单引号字符串和转义引用
双引号或单引号字符串里面可以包含另外一种符号,不需要转义,否则用\转义。
2、拼接字符串
挨着写两个字符串会自动连接 【只限于字符串本身,变量不行】
加法运算可以用于拼接字符串
3、字符串表示str和repr
使用str,python会把值转换成合理形式的字符串,以便用户可以理解;
而repr会创建一个字符串,它以合法的python表达式形式来表示值。【区别就在于表达式】
>>> print repr("Hello, world")
'Hello, world'
>>> print repr(1000L)
1000L
>>> print str("Hello, world")
Hello, world
>>> print str(1000L)
1000
repr(x)的功能也可以用来实现`X`(反引号),如果希望打印一个包含数字的语句,反引号就比较有用额,但3.0已经不支持了,可以用repr代替
>>> temp = 42
>>> print "The temperature is " + temp
Traceback (most recent call last):
File "", line 1, in
print "The temperature is " + temp
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "The temperature is " + `temp`
The temperature is 42
4、input和raw_input对比
input 会【假设】用户输入的事合法的Python表达式。
而raw_input会把所有的输入当做原始数据(raw data),然后将其放入字符串中:
>>> name = input("What is your name?")
What is your name?jason
Traceback (most recent call last):
File "", line 1, in
name = input("What is your name?")
File "", line 1, in
NameError: name 'jason' is not defined
>>> input("Enter a number:")
Enter a number:3
3
>>> raw_input("Enter a number:")
Enter a number:3
'3'
5、长字符串、原始字符串和Unicode
》长字符串:
’‘’ ** ‘’‘ 可以跨行,不需要转义其中引号
》原始字符串:
对于路径的情况,往往需要将所有的\换成\\,这样需要复制之后做很多添加,原始字符串可以解决这个问题
>>> print 'F:\python\npython\Doc'
F:\python
python\Doc
>>> print r'F:\python\npython\Doc'
F:\python\npython\Doc
》Unicode字符串:
Python中的普通字符串在内部是以8位ASCII码形成存储的。
>>> temp = ['temp1','temp2']
>>> print temp
['temp1', 'temp2']
>>> temp = [u'temp1',u'temp2']
>>> print temp
[u'temp1', u'temp2']