type():
在介绍数据类型的文章中提到过,要怎么样查看对像的数据类型。type()就是一个最实用又简单的查看数据类型的方法。type()是一个内建的函数,调用它就能够得到一个反回值,从而知道想要查询的对像类型信息。
dir():
中文说明:
不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
参数object:
对象、变量、类型。
版本:
该函数在python各个版本中都有,但是每个版本中显示的属性细节有所不同。使用时注意区别。
name = str('eric')# 默认会执行str类的__init__方法
查看类里所有的成员:
name = 'eric'
print(type(name))
print(dir(name))
输出:
<class 'str'>
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
1、判断包含: def __contains__(self, *args, **kwargs): # real signature unknown """ Return key in self. """ pass 实例: name = str('eric')# 默认会执行str类的__init__方法 #result = name.__contains__('er')#判断包含 result = 'er' in name#相当于result = name.__contains__('er')
print(result)
2、判断相等:
def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass 实例: name = ("eric") result = name.__eq__('eric') print(result)
3、首字母大写:
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 "" 实例: name = 'eric' result = name.capitalize() print(result)
4、首字母大写改小写:
def casefold(self): # real signature unknown; restored from __doc__ """ S.casefold() -> str Return a version of S suitable for caseless comparisons. """ return ""
5、居中 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 " 实例: name = 'eric' result = name.center(20,'*') print(result) ********eric********
6.Python 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 例1: name = "lsdjksjdlsdjlaSKJ DLSJD" result = name.count('d') print(result) 得3 例2: name = "lsdjksjdlsdjlaSKJ DLldSldJD" result = name.count('ld') print(result) 得2 例3规定查找的起始位置和结束位置: name = "lsldjksjdlsdjlaSKJ DLldSldJD" result = name.count('ld',0,10) print(result) 得1
7、编码: 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"" 例子: name = "时间" result = name.encode('gbk') print(result)
得:b'xcaxb1xbcxe4'
8、endswith()方法: Python endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。 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 例子: name = "shijian" result = name.endswith('e') result1 = name.endswith('n') result2 = name.endswith('an') result3 = name.endswith('i',0,3) print(result) print(result1) print(result2) print(result3) 得: False True True True
9、函数原型:find(str, pos_start, pos_end) 解释: str:被查找“字串” pos_start:查找的首字母位置(从0开始计数。默认:0) pos_end: 查找的末尾位置(默认-1) 返回值:如果查到:返回查找的第一个出现的位置。否则,返回-1。
index 也是查找、如果找不到就直接报错。 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 例: name = 'alex' result = name.find('x') print(result)
10、格式化字符串它通过{}和:来代替%。:
def format(self, *args, **kwargs): # known special case of str.format
"""
S.format(*args, **kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
"""
例子:
name = "alex {0}"
result = name.format('boy')
print(result)
得:
alex boy
例2:
name = "alex {0} as {1}"
result = name.format('boy','girl')
print(result)
动态参数:
name = "alex {name} as {id}"
result = name.format(name = 'boy',id = 'girl')
print(result)
判断: 判断是否是字母或者是数字 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 判断是否是字母 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 判断是否是十进制小数: def isdecimal(self): # real signature unknown; restored from __doc__ """ S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise. """ return False 判断是否是数字: 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 关键字? 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 判断全部是否是小写: 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 判断是否是数字: 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 是否可以打印? 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 判断是否是空格: 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 字符串是不是标题: 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 是否全部是大写: 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
Python中的join()函数的用法 函数:string.join() Python中有join()和os.path.join()两个函数,具体作用如下: join(): 连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串 os.path.join(): 将多个路径组合后返回 一、函数说明 1、join()函数 语法: 'sep'.join(seq) 参数说明 sep:分隔符。可以为空 seq:要连接的元素序列、字符串、元组、字典 上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串 返回值:返回一个以分隔符sep连接各个元素后生成的字符串 2、os.path.join()函数 语法: os.path.join(path1[,path2[,......]]) 返回值:将多个路径组合后返回 注:第一个绝对路径之前的参数将被忽略 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 "" 例: l = ['x','i','a','o','l','o','n','g'] result = "_".join(l) print(result) 得: x_i_a_o_l_o_n_g
左对齐: 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 "" 右对齐: 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 ""
转小写: def lower(self): # real signature unknown; restored from __doc__ """ S.lower() -> str Return a copy of the string S converted to lowercase. """ return ""
去掉左边空格:
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 ""
对应表???(3.0 能用?):
两个结合着使用
Python maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
注:两个字符串的长度必须相同,为一一对应的关系。
语法
maketrans()方法语法:
str.maketrans(intab, outtab)
参数
-
- intab -- 字符串中要替代的字符组成的字符串。
- outtab -- 相应的映射字符的字符串。
返回值
返回字符串转换后生成的新字符串。
实例
以下实例展示了使用maketrans() 方法将所有元音字母转换为指定的数字:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from string import maketrans # 必须调用 maketrans 函数。
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab);
以上实例输出结果如下:
th3s 3s str3ng 2x1mpl2....w4w!!!
def maketrans(self, *args, **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 def translate(self, table): # real signature unknown; restored from __doc__ """ S.translate(table) -> str Return a copy of the string S, where all characters have been mapped through the given translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None. Unmapped characters are left untouched. Characters mapped to None are deleted. """ return ""
Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。 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 "" 例: name = "xiaolongisboy" result = name.replace('a','o') print(result) 得: xioolongisboy
例:
name = "xiaolongaisboya"
result = name.replace('a','o',2)
print(result)
得:
xioolongoisboya
从右到左找: 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 从右到左找: 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 右对齐: 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 ""
partition() 方法用来根据指定的分隔符将字符串进行分割。 如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。 partition() 方法是在2.5版中新增的。 def rpartition(self, sep): # real signature unknown; restored from __doc__ """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass
描述
Python split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
语法
split()方法语法:
str.split(str="", num=string.count(str)).
参数
- str -- 分隔符,默认为所有的空字符,包括空格、换行( )、制表符( )等。
- num -- 分割次数。
返回值
返回分割后的字符串列表。
实例
以下实例展示了split()函数的使用方法:
#!/usr/bin/python
str = "Line1-abcdef
Line2-abc
Line4-abcd";
print str.split( );
print str.split(' ', 1 );
以上实例输出结果如下:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '
Line2-abc
Line4-abcd']
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 []
根据换行符: 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 [] 例: name = ''' aa bb cc''' result =name.splitlines() print(result) 得: ['', 'aa', 'bb', 'cc']
name = '''
aa
bb
cc'''
result =name.split(" ")
print(result)
转换大小写: 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 ""
大写: def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> str Return a copy of S converted to uppercase. """ return ""