第一章字符串
单引号字符串
*例:
print ("Hello,World")
Hello,World
mystring=("Hello,World!")
mystring
'Hello,World!'
mystr2='Hello,World! 2'
mystr2
'Hello,World! 2'*
注:单引号和双引号引的是字符串,单引号和双引号没有区别,但要保持字符串前后一致
在Python 2.6中不需要加括号,在Python 3.6中必须加括号,否则报错
例:
"Let's go!"
"Let's go!"
'asd "fgh" jkl'
'asd "fgh" jkl'
'Let's go!'
"Let's go!"
如果字符串中需要使用单引号(或双引号)可以将字符串前后使用双引号(或单引号);或者使用转义字符
拼接字符串
*例:
a="Hello"
b="World!"
a+b
'HelloWorld!'*
**注:“+”用于连接字符串,如果改成空格将报错
字符串表示( str 和 repr )
*例:>>> mystring='HelloWorld!'
print (mystring)
HelloWorld!
print (repr (mystring))
'HelloWorld!'
** repr()的作用是将括号里的字符串转为Python中合法的表达式
str()是把括号里的对象变成字符串**
input和让raw_input的比较
*例:
name=input("What is your name?")
What is your name?
name=input("What is your name?")
What is your name?"Tom"
name
'"Tom"'
input("Enter a number:")
Enter a number:5
'5'
注:用input()时,若输入的是名字或者其他未定义的字符,则需要加上引号
若用raw_input()则不需要,故需由用户输入时应使用raw_input,但是从Python3开始raw_input()和input()整合为input()
长字符串、原始字符串和unicode字符串
*例:
print ('''this is a very string''')
this is a very string
print ('''this is a very string
It continues here
And it's notover yet.
"HolloWord"
still here.''')
this is a very string
It continues here
And it's notover yet.
"HolloWord"
still here.
path='a\nb'
print (path)
a
b
path=r'a\nb'
print (path)
a\nb*
path=r'a\nb\'
print (path)
a\nb\
注:
前后的六个引号要相同,在长字符串中的引号不需要转义,但是其他的需要转义
若在定义变量时在等号后,引号前加个“r”就会对后面引号内的字符串中的内容不进行转义,但是如果斜线在最后则必须进行转义
*例:
path=u'梁'
print (path)
梁
注:
unicode字符适用于非英文或者数字或者符号,例如中文
使用的时候只需在等号后,引号前加一个“u”