复习数据类型
数
Python中的数分为整型、长整型、浮点型与复数,一般情况下数和字符串用的比较多点。
整型与浮点型的概念与C语言相同,需要注意的是在Python3中8进制与2进制整型的表示方式发生了变化,比如在Python2中八进制0777,在Python3中表示为0o777;Python3中二进制表示1011为0b1011。在Python3中长整型被整型所取代。
关于复数的话,与数学中的基本一致,形如8+9j,其中8为实部,9为虚部,之后的运算方式与数学中法则一致。
字符串
Python中的字符串与C++ STL中的string类型相仿,可以直接赋值,比如str = "this is a string"
。当然如果学过PHP语言的话,可能对Python中字符串引号的格式有所熟悉,字符串可以通过单引号''
、双引号""
、三引号'''
进行声明。单引号与多引号的使用可以使字符串中出现引号的地方不需用转义字符,比如下面这个例子:
#单双引号的使用可以避免使用过多的转义字符
statement = "It's a dog"
#如果只用单引号
statement = 'It\'s a dog'
三引号的使用可以将字符串声明为一段文字,比如一般情况下程序的Usage:
usage = '''
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.
Mandatory arguments to long options are mandatory for short options too.
-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask
-p, --parents no error if existing, make parent directories as needed
-v, --verbose print a message for each created directory
-Z set SELinux security context of each created directory
to the default type
--context[=CTX] like -Z, or if CTX is specified then set the SELinux
or SMACK security context to CTX
--help display this help and exit
--version output version information and exit
GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Full documentation at: <http://www.gnu.org/software/coreutils/mkdir>
or available locally via: info '(coreutils) mkdir invocation'
'''
当然,字符串也会像C++一样存在很多的函数,比如基本的拼接、截取、查找、替换。
str1 = 'hello '
str2 = 'world'
#字符串拼接
str3 = str1 + str2
#字符串截取
#使用[start : end]获取截取的范围从start到end,当然数值为负数时表示从末尾开始的位置
str4 = str1[2:] #第2个字符到最后
str5 = str1[2] #取第2个字符
str6 = str1[:-1] #从头到倒数第2个字符
#字符串查找
pos = str1.index('ll') #这样做当源字符串中不存在目标字符串时会抛出异常,rindex为从右自左查找
isHas = str1.find('ll') #查找源字符串中是否有目标字符串,rfind为从右自左查找
#字符串替换
str7 = str1.replace('world', 'python')