标签:
字符串是很重要的一种数据类型,今天我们就一起来看str的内在。
1. 字符串的声明
myname="ben" yourname=str("Jin") print("myname的值是%s,类型为%s" %(myname,type(myname))) print("yourname的值是%s,内部成员为%s" %(yourname,dir(myname))) ========================================== 返回结果: myname的值是ben,类型为<class ‘str‘> yourname的值是Jin,内部成员为[‘__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‘]
2. __init__ 构造方法 yourname=str("Jin")生成对象的时候运行的就是__init__
3.__contains__ 是否包含
myname="Ben" result=myname.__contains__("en") print(result) =========================== 返回结果:True
4.__getattribute__ 反射 无条件被调用,通过实例访问属性。如果class中定义了__getattr__(),则__getattr__()不会被调用(除非显示调用或引发AttributeError异常)
5. __getitem__ dic[1]实际执行的就是字典的__getitem__方法
6. capitalize首字母大小写
myname="ben" result=myname.capitalize() print(result) =================================== 运行结果 Ben
7. casefold 跟lower类似,讲字符串变成小写,不过不只是针对ASCII,也可以将一些德文之类的变成小写。汉语 & 英语环境下面,继续用 lower()
没问题;要处理其它语言且存在大小写情况的时候再用casefold()
8. center 将字符串居中,并用其他字符包围
myname="ben" result=myname.center(20,"*") print(result) =========================== 返回结果: ********ben*********
9. count 计算字符串的一部分出现的次数
myname="benbenben" result=myname.count("ben",2,9) print(result) ========================= 返回结果:2
10. endwith 判断是否以某字符串结尾
myname="benbenben" result=myname.endswith("ben",2,9) print(result) ============================== 返回结果: True
11. encode
myname="陈真" ##utf8 result=myname.encode("gbk") ##内部是先转成unicode 然后转成gbk print(result) ================================= 返回结果:b‘\xb3\xc2\xd5\xe6‘
标签:
原文地址:http://www.cnblogs.com/benchen/p/5781959.html