Python的一些小知识点


Python生成GUID

>>> import uuid
>>> uuid.uuid1()
UUID('5a35a426-f7ce-11dd-abd2-0017f227cfc7')

#Python中的string对象有几个常用的方法用来输出各种不同的字符:

string.ascii_letters    #输出ascii码的所有字符
string.digits           #输出 '0123456789'.
string.punctuation      #ascii中的标点符号
print string.ascii_letters
print string.digits
print string.punctuation

#输出结果如下:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
!"#$%&'()*+,-./:;<=>?@[]^_`{|}~

#下面的代码用于生成随机密码:

import string
from random import *
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(characters) for x in range(randint(8, 16)))
print password

Python判断变量类型

python判断变量类型时,为什么不推荐使用type()方法

实际上还有一种方法是用isinstance。比如:

a = 111
isinstance(a, int)
True

isinstance 和 type的区别在于:

class A:
    pass
class B(A):
    pass

isinstance(A(), A)  # returns True
type(A()) == A      # returns True
isinstance(B(), A)    # returns True
type(B()) == A        # returns False

区别就是 对于subclass之类的 type 就不省事了。

参考链接:python判断变量类型时,为什么不推荐使用type()方法 – SegmentFault http://segmentfault.com/q/1010000000127305


Python可以得到一个对象的类型 ,利用type函数:

>>>lst = [1, 2, 3]
>>>type(lst)
<type 'list'>

不仅如此,还可以利用isinstance函数,来判断一个对象是否是一个已知的类型。isinstance说明如下:

  isinstance(object, class-or-type-or-tuple) -> bool

Return whether an object is an instance of a class or of a subclass thereof.

With a type as second argument, return whether that is the object’s type.

The form using a tuple, isinstance(x, (A, B, …)), is a shortcut for isinstance(x, A)

or isinstance(x, B) or … (etc.).

其第一个参数为对象,第二个为类型名或类型名的一个列表。其返回值为布尔型。

若对象的类型与参数二的类型相同则返回True。若参数二为一个元组,则若对象类型与元组中类型名之一相同即返回True。

>>>isinstance(lst, list)
  Trueisinstance(lst, (int, str, list))
  True
>>>isinstance(lst, (int, str, list))
  True

这也算Python的强大之一吧!


Python中的dictjson格式的一些

Json概述以及python对json的相关操作

在Python标准库的json包中,提供了JSONEncoder和JSONDecoder两个类来实现Json字符串和dict类型数据的互相转换。

Python 将字符串转换成字典dict

JSON到字典转化:
dictinfo = simplejson.loads(json_str)   #输出dict类型

字典到JSON转化:
jsoninfo = simplejson.dumps(dict)   #输出str类型

比如:

info = {'name' : 'jay', 'sex' : 'male', 'age': 22}
jsoninfo = simplejson.dumps(info)
print jsoninfo
print type(jsoninfo)

Python中的强制类型转换


Python中进行字符串替换的2种方法

  • 是用字符串本身的replace()方法。
  • 用正则的sub()函数来替换。

下面用个例子来实验下:
a = ‘hello word’
我把a字符串里的word替换为python。

1.用字符串本身的replace方法:
a = a.replace(‘word’, ‘python’)
输出的结果是hello python

2.用正则表达式来完成替换:
import re
strinfo = re.compile(‘word’)
b = strinfo.sub(‘python’, a)
print b
输出的结果也是hello python

至于用哪个方法的话,看你自己的选择了(顺便说一句,在Python中处理字符串的时候,使用字符串自身的方法速度是最快的)。


 

Python连接字符串的几种方法
方法1:直接通过加号操作符相加
foobar = 'foo' + 'bar'

低效原因:在使用”+”连接字符串的时候,每次连接一次,就要重新开辟空间,然后把字符串连接起来,再放入新的空间,再一次循环,又要开辟新的空间,把字符串连接起来放入新的空间,如此反复,内存操作比较频繁,每次都要计算内存空间,然后开辟内存空间,再释放内存空间,效率非常低,你也许操作比较少的数据的时候看不出来,感觉影响不大,但是你碰到操作数据量比较多的时候,这个方法就要退休了。

方法2:join方法
list_of_strings = ['abc', 'def', 'ghi']
foobar = ''.join(list_of_strings)
方法3:替换
foobar = '%s, %s' % ('abc', 'def')
foobar = '%s%s' % ('abc', 'def')
参考链接:
,

《“Python的一些小知识点”》 有 4 条评论

  1. UUID字符串的标准格式及匹配正则
    https://stackoverflow.com/questions/10687505/uuid-format-8-4-4-4-12-why
    http://www.ietf.org/rfc/rfc4122.txt
    `
    It’s separated by time, version, clock_seq_hi, clock_seq_lo, node, as indicated in the followoing rfc4122.

    8-4-4-4-12
    `
    https://en.wikipedia.org/wiki/Universally_unique_identifier
    https://stackoverflow.com/questions/11384589/what-is-the-correct-regex-for-matching-values-generated-by-uuid-uuid4-hex
    `
    import re
    uuid4hex = re.compile(‘[0-9a-f]{32}\Z’, re.I)

    ####

    uri = re.sub(r'[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[1-5][a-fA-F0-9]{3}-[89ab][a-fA-F0-9]{3}-[a-fA-F0-9]{12}’, ‘{uuid}’, uri)
    uri = re.sub(r'[a-fA-F0-9]{32}’, ‘{uuid}’, uri)
    `

回复 a-z 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注