Python菜鸟之路基础篇(二)

简单模块初识

很多人都说Python的扩展性很强,有很多第三方的类库,那这些类库到底怎么使用呢,其实在Python语言中不管是内置的类库和其他开发扩展的类库,在Python中我们习惯把它叫做「模块」。那模块该怎么用呢?不着急下面我们简单介绍几个常用的内库「内裤吗?」。 1、sys (系统内裤)
#!/usr/bin/env python3
# _[i]_coding:utf-8_[/i]_
# Author: Lucky.chen

import sys

# Python全局环境变量路径
print(sys.path)

# 打印传递给脚本的第二个参数
print(sys.argv[2])
Result:
['/Users/crh/PycharmProjects/app', '/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python35.zip', '/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5', '/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin', '/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/site-packages']
2
说明一下Python的环境变量,比如我们导入一个模块它先到你本路径找有没有,然后回到Python的环境路径下再去找,一般扩展的模块安装后都会在site-packages的路径下。   2、os(系统内裤)
#!/usr/bin/env python3
# _[i]_coding:utf-8_[/i]_
# Author: Lucky.chen

import os
 
# 调用系统命令
os.system("df -h")
Result:
Filesystem      Size   Used  Avail Capacity  iused    ifree %iused  Mounted on
/dev/disk1     233Gi   80Gi  153Gi    35% 20947137 40038205   34%   /
devfs          181Ki  181Ki    0Bi   100%      626        0  100%   /dev
map -hosts       0Bi    0Bi    0Bi   100%        0        0  100%   /net
map auto_home    0Bi    0Bi    0Bi   100%        0        0  100%   /home
3、sys、os结合玩一玩
#!/usr/bin/env python3
# _[i]_coding:utf-8_[/i]_
# Author: Lucky.chen

import os
import sys

# 把用户传入的参数当做命令执行
os.system(''.join(sys.argv[1:]))
  4、自己编写简单模块 Python tab补全模块: Linux版本:
#!/usr/bin/env python3 
# python startup file 
import sys
import readline
import rlcompleter
import atexit
import os
# tab completion 
readline.parse_and_bind('tab: complete')
# history file 
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter
Mac版:
# linux and python3 on mac
import sys
import readline
import rlcompleter

if sys.platform == 'darwin' and sys.version_info[0] == 2:
    readline.parse_and_bind("bind ^I rl_complete")
else:
    readline.parse_and_bind("tab: complete")  
写完保存后就可以导入使用:
>>> import tab
[quote]>> import os
>>> os.
Display all 234 possibilities? (y or n) 
>>> os.sy
os.symlink(      os.sys           os.sysconf(      os.sysconf_names os.system(      
>>> os.sy
os.symlink(      os.sys           os.sysconf(      os.sysconf_names os.system(      
>>> os.sy
你会发现,上面自己写的tab.py模块只能在当前目录下导入,如果想在系统的何何一个地方都使用怎么办呢? 此时你就要把这个tab.py放到python全局环境变量目录里啦,基本一般都放在一个叫 site-packages 目录下,这个目录在不同的OS里放的位置不一样,用 print(sys.path) 可以查看python环境变量列表。  

基础数据类型认识

A、数字
2 是一个整数的例子。
长整数 不过是大一些的整数。
3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 * 10-4。
(-5+4j)和(2.3-4.6j)是复数的例子,其中-5,4为实数,j为虚数,数学中表示复数是什么?。
数学中表示复数的虚数是n,而Python中跟大数据计算一样统一用的是j。   1、int(整型
在32位机器上,整数的位数为32位,取值范围为-2[b]31~2[/b]31-1,即-2147483648~2147483647
在64位系统上,整数的位数为64位,取值范围为-2[b]63~2[/b]63-1,即-9223372036854775808~9223372036854775807
所以不同的操作系统中数据的长度是有限制范围的,就好像32位系统最多支持4GB内存一样。   在我们里面12、34、56、100000等都是整型。
#!/usr/bin/env python3
# _[i]_coding:utf-8_[/i]_
# Author: Lucky.chen[/quote]

a = '3'
print(type(a))

b = int(a)
print(type(a))
其他具体功能可以查看帮助: [attach]1310[/attach]   2、long(长整型)
跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。
注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。
如:9223372036854775808、922337203685477580800  默认在Python2版本里面超过263 就是长整型,而Python3.中都是整型。
>>> print(type(2[/b]63))

[quote]>> print(type(2**62))
 [b]3、float(浮点型)
浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。
例如:1.2 、0.98、100.38 都是浮点类型
#!/usr/bin/env python3
# _[i]_coding:utf-8_[/i]_
# Author: Lucky.chen[/quote]

a = 3
print(type(a))

b = float(a)

print(type(b), b)

 3.0
具体更多功能查看帮助: [attach]1311[/attach] 4、complex(复数)
复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。
注:Python中存在小数字池:-5 ~ 257 比如:1+2j,3+6j等都是复数
#!/usr/bin/env python3
# _[i]_coding:utf-8_[/i]_
# Author: Lucky.chen

a = (3-4j).conjugate()

print(a)

print(type(a))

# 结果
(3+4j)
具体更多功能查看帮助: [attach]1312[/attach] B、布尔值
在Python的世界里面有一个叫布尔值的东西,其实就是 真或假 1 或 0,简单点就是True和False。
在其他的配置或者语言里面,我们都知道把某个东西打开需要把他调试为True,关闭则设置为False。
在Python里面也是一样True就代表为真,条件成立;False就代表为假,条件不成立;1代表为真,0
代表假。
#!/usr/bin/env python3
# _[i]_coding:utf-8_[/i]_
# Author: Lucky.chen

a, b = 1, 0

if a:
    print("a is True")
else:
    print("a is False")

if b:
    print("b is True")
else:
    print("b is False")
    
# 结果
a is True
b is False
C、字符串 1、拼接 在之前的文章http://openskill.cn/article/415  里已经介绍过了字符串拼接的方法如:+  %  format函数等。
Python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间。
所以最好不要用+比较好
name = "lucky"
print "i am %s " % name
  
#输出: i am lucky
PS: 字符串是 %s;整数 %d;浮点数%f 2、字符串常用功能介绍 移除空白rstrip 去掉右边的空格以及tab制表符
def rstrip(self, [i]args, [/i]*kwargs): # real signature unknown
        """
        Strip trailing bytes contained in the argument.
        
        If the argument is omitted or None, strip trailing ASCII whitespace.
        """
        pass
msg = "  my name is lucky   "

print("[i][b][/i]" + msg.lstrip() + "[/b]*")

Result:
[i][b][/i]  my name is lucky[/b]*
lstrip 去掉左边的空格以及tab制表符
def lstrip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.lstrip([chars]) -> str
        
        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
msg = "  my name is lucky   "
info = "     game is\tlol\tover!"

print("[b][i]" + msg.lstrip() + "[/b][/i]")
print("[b][i]" + info.lstrip() + "[/b][/i]")

Result:
[b][i]my name is lucky   [/b][/i]
[b][i]game is	lol	over![/b][/i]
strip 去除字符串两边的空格和换行
def strip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.strip([chars]) -> str
        
        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
msg = "  ox\nB  "

print("[b][i]" + msg.strip() + "[/b][/i]")

Result:
***ox
B***
分割: splitlines 使用回车符进行字符串分片,最后得到一个列表
def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
        """
        S.splitlines([keepends]) -> list of strings
        
        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return 
msg = "niu\nbai"
print(msg.splitlines())

Result:
['niu', 'bai']
rsplit 是从右开始切片,当不指定从哪个分隔符数开始,默认和split没有区别,但是指定了从第几个分隔符之后,就会有所不同了
def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.rsplit(sep=None, maxsplit=-1) -> list of strings
        
        Return a list of the words in S, using sep as the
        delimiter string, starting at the end of the string and
        working to the front.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified, any whitespace string
        is a separator.
        """
        return 
msg = "wo is wo wo tou wo is wo is lucky"
print(msg.rsplit('wo', 2))

Result:
['wo is wo wo tou ', ' is ', ' is lucky']

从0开始数,到第二个wo之后开始分隔。
split 使用指定分隔符对字符串进行分割,最后得到一个列表
def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.split(sep=None, maxsplit=-1) -> list of strings
        
        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return 
msg = "1a2a3a4a5"
print(msg.split('a'))

Result:
['1', '2', '3', '4', '5']
长度: ljust 打印固定长度的字符串,如果不够在字符串的右边补全指定字符达到制定长度
def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.ljust(width[, fillchar]) -> str
        
        Return S left-justified in a Unicode string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""
msg = "lucky"
print(msg.ljust(30, 'G'))

Result:
luckyGGGGGGGGGGGGGGGGGGGGGGGGG
rjust 打印固定长度的字符串,如果不够在字符串的左边补充指定字符
def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.rjust(width[, fillchar]) -> str
        
        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""
msg = "lucky"
print(msg.rjust(30, 'G'))

Result:
GGGGGGGGGGGGGGGGGGGGGGGGGlucky
zfill 打印指定长度字符串,不够的使用0在左边补全
def zfill(self, width): # real signature unknown; restored from __doc__
        """
        S.zfill(width) -> str
        
        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        """
        return ""
msg = "lucky"
print(msg.zfill(30))

Result:
0000000000000000000000000lucky
索引: find  查找一个字符或字符组合在一个字符串中的索引位置,索引位置从0开始,而且找到了第一个就不会往下找了,字符串可以根据索引进行切片
def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int
        
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
        
        Return -1 on failure.
        """
        return 0
msg = "lucky.chen@126.com"
print(msg.find('c'))
print("[i]" [/i] 20)
print(msg.find('c', 3, 10))
print("[i]" [/i] 20)
print(msg.find('c', 8, 19))

Result:
2
********************
6
********************
15
index 返回某个字符在字符串中的下标
def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int
        
        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0
name = 'lucky'
print(name.index('u'))
print(name.index('c', 0, 4))

Result:
1
2
rfind 查找一个字符串中某个字符所在的索引,如果这个字符串中有多个这个字符,那么会找到最右边的那个字符
def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rfind(sub[, start[, end]]) -> int
        
        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
        
        Return -1 on failure.
        """
        return 0
msg = "lucky.chen@126.com"
print(msg.rfind('c'))
print("[i]" [/i] 10)
print(msg.rfind('c', 1, 6))


if msg.rfind('c', 22, 23) == -1:
    print("failure")
else:
    print("OK")
    
Result:
15
**********
2
failure
rindex 跟rfind差不多
def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.rindex(sub[, start[, end]]) -> int
        
        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0
msg = "lucky.chen@126.com"
print(msg.rindex('c'))
print("[i]" [/i] 10)
print(msg.rindex('c', 1, 6))

Result:
15
**********
2
大小写capitalize 大写字符串首字母
def capitalize(self): # real signature unknown; restored from __doc__
        """
        S.capitalize() -> str
        
        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""
msg = "lol"

print(msg.capitalize())

Result:
Lol
islower  判断字符串是不是不包含大写,返回是布尔值
def islower(self): # real signature unknown; restored from __doc__
        """
        S.islower() -> bool
        
        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False
msg = "lol"
print(msg.islower())
print("[i]" [/i] 10)
msg = "Wo I Lol"
print(msg.islower())

Result:
True
**********
False
istitle 判断一个字符串是否为title,字符串首字母大写就为title,返回时布尔值
def istitle(self): # real signature unknown; restored from __doc__
        """
        S.istitle() -> bool
        
        Return True if S is a titlecased string and there is at least one
        character in S, i.e. upper- and titlecase characters may only
        follow uncased characters and lowercase characters only cased ones.
        Return False otherwise.
        """
        return False
msg = "lol"
print(msg.istitle())
print("[i]" [/i] 10)
msg = "Wo I Lol"
print(msg.istitle())

Result:
False
**********
True
isupper 判断字符串是否为全部大写,返回布尔值
def isupper(self): # real signature unknown; restored from __doc__
        """
        S.isupper() -> bool
        
        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False
msg = "12lol"
print(msg.isupper())
print("[i]" [/i] 10)
msg = "Wo I Lol"
print(msg.isupper())
print("[i]" [/i] 10)
msg = "12WINE"
print(msg.isupper())

Result:
False
**********
False
**********
True
upper 把字符串都变换为大写
def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str
        
        Return a copy of S converted to uppercase.
        """
        return ""
msg = "12lol"
print(msg.upper())
msg = "  Lucky is Good!  "
print("[size=16]#" + msg.upper() + "[/size]#")

Result:
12LOL
[size=16]#  LUCKY IS GOOD!  [/size]#
lower  把所有的字符串都变为小写
def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str
        
        Return a copy of the string S converted to lowercase.
        """
        return ""
msg = "12lol"
print(msg.lower())
msg = "  Lucky is Good!  "
print("[size=16]#" + msg.lower() + "[/size]#")

Result:
12lol
[size=16]#  lucky is good!  [/size]#
swapcase 大小写互换
def swapcase(self): # real signature unknown; restored from __doc__
        """
        S.swapcase() -> str
        
        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""
msg = "12lOl"
print(msg.swapcase())
msg = "  Lucky is Good!  "
print("[size=16]#" + msg.swapcase() + "[/size]#")

Result:
12LoL
[size=16]#  lUCKY IS gOOD!  [/size]#
判断: isalnum 判断这个字符串是否为单单有阿拉伯字母和数字组成,返回布尔值
def isalnum(self): # real signature unknown; restored from __doc__
        """
        S.isalnum() -> bool
        
        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False
sb = "123xx^ff"
ub = "123meting"
u = "123"
b = "meting"

print(sb.isalnum())
print(ub.isalnum())
print(u.isalnum())
print(b.isalnum())

Result:
False
True
True
True
isalpha 判断字符串是否由纯英文,包括大小字母,返回布尔值
def isalpha(self): # real signature unknown; restored from __doc__
        """
        S.isalpha() -> bool
        
        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False
ub = "123meting"
u = "123"
b = "meting"

print(ub.isalpha())
print(u.isalpha())
print(b.isalpha())

Result:
False
False
True
isdigit 判断是不是一个整数,返回布尔值
def isdigit(self): # real signature unknown; restored from __doc__
        """
        S.isdigit() -> bool
        
        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False
ub = "123meting"
u = "123"
b = "123.0"

print(ub.isdigit())
print(u.isdigit())
print(b.isdigit())

Result:
False
True
False
isidentifier 判断是否是一个合法的标识符也可以叫做是否是一个合法的变量名
def isidentifier(self): # real signature unknown; restored from __doc__
        """
        S.isidentifier() -> bool
        
        Return True if S is a valid identifier according
        to the language definition.
        
        Use keyword.iskeyword() to test for reserved identifiers
        such as "def" and "class".
        """
        return False
ub = "123meting"
u = "Fun"
b = "123.0"

print(ub.isidentifier())
print(u.isidentifier())
print(b.isidentifier())

Result:
False
True
False
isnumeric 判断字符串是否只有数字,返回布尔值
def isnumeric(self): # real signature unknown; restored from __doc__
        """
        S.isnumeric() -> bool
        
        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return False
ub = "123meting"
u = "123.0"
b = "123"

print(ub.isnumeric())
print(u.isnumeric())
print(b.isnumeric())

Result:
False
False
True
isprintable 如果字符串中有制表符\t,返回布尔值
def isprintable(self): # real signature unknown; restored from __doc__
        """
        S.isprintable() -> bool
        
        Return True if all characters in S are considered
        printable in repr() or S is empty, False otherwise.
        """
        return False
msg = "Lucky is Good\t Man"

if msg.isprintable():
    print(msg)
else:
    print("have 制表符")
    
Result:
have 制表符
isspace 判断字符串是否是一个以上空格,返回布尔值
def isspace(self): # real signature unknown; restored from __doc__
        """
        S.isspace() -> bool
        
        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False
msg = " "   # 一个空格
if msg.isspace():
    print("是空格")
else:
    print("不是空格")

msg = "   "   # 三个空格
if msg.isspace():
    print("是空格")
else:
    print("不是空格")
    
Result:
是空格
是空格
 其他: count 统计字符串中某个字符出现的次数,返回整型结果
def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.count(sub[, start[, end]]) -> int
        
        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0
msg = "lucky.chen@126.com"
print(msg.count('c'))
print("[i]" [/i] 10)
print(msg.count('c', 3, 8))

Result:
3
**********
1
center 美观打印,打印包括现有变量在内的30个字符串, 如果字符串不够实用相应的字符前后补全
def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.center(width[, fillchar]) -> str
        
        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""
msg = "Shopping List"
print(msg.center(50, '*'))

Result:
**************[i][b][/i]Shopping List[/b]*****************
encond 编码转换,在py3中把字符串转为二进制
def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
        """
        S.encode(encoding='utf-8', errors='strict') -> bytes
        
        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""
msg = "葫芦娃"
print(msg.encode(encoding='utf-8', errors='strict'))

Result:
b'\xe8\x91\xab\xe8\x8a\xa6\xe5\xa8\x83'
endswith 判断一个字符串以什么结尾,返回布尔值
def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool
        
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False
msg = "lucky.chen@126.com"

if msg.endswith('126.com'):
    print("Mail is True")
else:
    print("Mail is False")

if msg.endswith('@', 8, 11):
    print(msg.find('@', 8, 11))
    
Result:
Mail is True
10
expandtabs  如果字符串中包含一个\t的字符,如果包含则把\t变成8个空格,当然也可以指定个数
def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
        """
        S.expandtabs(tabsize=8) -> str
        
        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""
msg = "Lol is\tGood Game"
print(msg.expandtabs())
print(msg.expandtabs(tabsize=1))
print(msg.expandtabs(tabsize=20))

Result:
Lol is  Good Game
Lol is Good Game
Lol is              Good Game
format 这是一种文件格式化的输出,可以是变量值也可以是下标索引的方法
def format([i]args, [/i]*kwargs): # known special case of str.format
        """
        S.format([i]args, [/i]*kwargs) -> str
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass
msg = """**********[i][b][/i] Shopping List [/b]*************
book: {Book}
bike: {Bike}
food: {Food} """

print(msg.format(Book=1, Bike=2, Food=3))

print("#" * 50)

msg = """**********[i][b][/i] Shopping List [/b]*************
book: {0}
bike: {1}
food: {1} """

print(msg.format(100, 200))

Result:
**********[i][b][/i] Shopping List [/b]*************
book: 1
bike: 2
food: 3 
###############################################[size=16]#[/size]
**********[i][b][/i] Shopping List [/b]*************
book: 100
bike: 200
food: 200 
format_map 其实跟format功能是一样的,只不过传入的是字典,这个也有一个好处,就是你希望把你字典中的数据格式化输出,直接传入字典就好。
def format_map(self, mapping): # real signature unknown; restored from __doc__
        """
        S.format_map(mapping) -> str
        
        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces ('{' and '}').
        """
        return ""
msg = """**********[i][b][/i] Shopping List [/b]*************
book: {Book}
bike: {Bike}
food: {Food} """

print(msg.format_map({'Book': 38, 'Bike': 800, 'Food': 1000}))

Result:
**********[i][b][/i] Shopping List [/b]*************
book: 38
bike: 800
food: 1000 
join 常用的方法,把一个列表拼成一个字符串,中间用某个字符串分隔
def join(self, iterable): # real signature unknown; restored from __doc__
        """
        S.join(iterable) -> str
        
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""
a = ['1', '2', '3', '4']  # 元素必须要是str类型
print(':'.join(a))

Result:
1:2:3:4
maketrans 这个方法要配合translate方法使用,对数据进行加密/反解
def maketrans(self, [i]args, [/i]*kwargs): # real signature unknown
        """
        Return a translation table usable for str.translate().
        
        If there is only one argument, it must be a dictionary mapping Unicode
        ordinals (integers) or characters to Unicode ordinals, strings or None.
        Character keys will be then converted to ordinals.
        If there are two arguments, they must be strings of equal length, and
        in the resulting dictionary, each character in x will be mapped to the
        character at the same position in y. If there is a third argument, it
        must be a string, whose characters will be mapped to None in the result.
        """
        pass
s = "Hello World!"
#加密
p = s.maketrans("abcdefg", "3!@#$%^")

print(p)

# 解密,打出真实的p的内容
print(s.translate(p))

Result:
{97: 51, 98: 33, 99: 64, 100: 35, 101: 36, 102: 37, 103: 94}
H$llo Worl#!
replace 替换字符串字符,也可以指定替换的次数
def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str
        
        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""
msg = 'abcbcacba'

print(msg.replace('a', 'w'))
print(msg.replace('a','c', 3))

Result:
wbcbcwcbw
cbcbcccbc
startswith 判断以什么开头,返回布尔值
def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool
        
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False
msg = "lucky"

print(msg.startswith('l'))
print(msg.startswith('c', 2, 4))

Result:
True
True
title 把一个字符串变为一个title,首字母大写
def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str
        
        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""
msg = " shopping list "
print(msg.title())

Result:
 Shopping List 
translate 配合maketrans进行字符串的交换
def translate(self, table): # real signature unknown; restored from __doc__
        """
        S.translate(table) -> str
        
        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""
name = "lucky"
f = name.maketrans('abcde', '12345')

# 加密文
print(f)

# 解密,明文
print('test'.translate(f))

Result:
{97: 49, 98: 50, 99: 51, 100: 52, 101: 53}
t5st
​bytes类型 Python 3最重要的新特性大概要算是对文本和二进制数据作了更为清晰的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的方式混用str和bytes(类似int和long之间自动转换),正是这使得两者的区分特别清晰。你不能拼接字符串和字节包,也无法在字节包里搜索字符串(反之亦然),也不能将字符串传入参数为字节包的函数(反之亦然)。这是件好事。不管怎样,字符串和字节包之间的界线是必然的,下面的图解非常重要,务请牢记于心: [attach]1313[/attach] 在python中二进制的数据都是bytes的数据类型,文本都是字符串的数据类型,字符串可以编码成字节包,而字节包可以解码成字符串:
#!/usr/bin/env python3
# _[i]_coding:utf-8_[/i]_
# Author: Lucky.chen

msg = "康师傅"

print(msg.encode("utf-8"))  # 如果不指定编码格式,默认为utf-8
# b'\xe5\xba\xb7\xe5\xb8\x88\xe5\x82\x85'

print(b'\xe5\xba\xb7\xe5\xb8\x88\xe5\x82\x85'.decode("utf-8"))
# 康师傅
 

数据运算

算数运算: [attach]1314[/attach]   比较运算: [attach]1315[/attach]   赋值运算: [attach]1316[/attach]   逻辑运算: [attach]1317[/attach]   成员运算: [attach]1318[/attach]   身份运算: [attach]1319[/attach]   位运算: [attach]1320[/attach]
#!/usr/bin/python
  
a = 60            # 60 = 0011 1100
b = 13            # 13 = 0000 1101
c = 0
  
c = a & b;        # 12 = 0000 1100
print "Line 1 - Value of c is ", c
  
c = a | b;        # 61 = 0011 1101
print "Line 2 - Value of c is ", c
  
c = a ^ b;        # 49 = 0011 0001
print "Line 3 - Value of c is ", c
  
c = ~a;           # -61 = 1100 0011
print "Line 4 - Value of c is ", c
  
c = a << 2;       # 240 = 1111 0000
print "Line 5 - Value of c is ", c
  
c = a >> 2;       # 15 = 0000 1111
print "Line 6 - Value of c is ", c
运算符优先级: [attach]1321[/attach] 更多内容参考:猛击这里!   三元运算:
result = 值1 if 条件 else 值2
如果条件为真:result = 值1 如果条件为假:result = 值2
#!/usr/bin/env python3
# _[i]_coding:utf-8_[/i]_
# Author: Lucky.chen

a, b, c = 1, 2, 3

d = a if a > b else c
# 如果a大于b 则把的值赋给d, 如果a不大于b, 则把c的值直接赋给d
print(d)

Result:
3
如果不熟悉这种方法,只能老实的写if ... elif .... else 语句等!

0 个评论

要回复文章请先登录注册