Python的一些小知识点_2


0.如何查看Python有哪些内建函数?

如何查看Python中有哪些builtin函数/方法?

进入IPython;
输入:from __builtin__ import [Tab] #{连续按Tab进行补全}

1.The Python Challenge
2.Unicode编码
#coding=utf-8
import sys
print sys.getdefaultencoding()      # --> ascii
u1 = '中国'
print type(u1), repr(u1)            # --> <type 'str'> '\xe4\xb8\xad\xe5\x9b\xbd'
u2 = u'中国2009'
print type(u2), repr(u2)            # --> <type 'unicode'> u'\u4e2d\u56fd2009'

# str --> unicode
print '# str --> unicode'
u1_1 = u1.decode('utf8')
print type(u1_1), repr(u1_1)        # --> <type 'unicode'> u'\u4e2d\u56fd'
u1_2 = unicode(u1, 'utf8')
print type(u1_2), repr(u1_2)        # --> <type 'unicode'> u'\u4e2d\u56fd'

# unicode --> str
print
print '# unicode --> str'
u2_1 = u2.encode('utf8')
print type(u2_1), repr(u2_1)        # --> <type 'str'> '\xe4\xb8\xad\xe5\x9b\xbd2009'
u2_2 = u2.encode('gbk')
print type(u2_2), repr(u2_2)        # --> <type 'str'> '\xd6\xd0\xb9\xfa2009'
u2_3 = u2.encode('gb2312')
print type(u2_3), repr(u2_3)        # --> <type 'str'> '\xd6\xd0\xb9\xfa2009'
3.Python和日期相关的代码{datetime模块}
import datetime
for day in range(30):
    print (datetime.datetime.today()-datetime.timedelta(days=day)).strftime('%Y-%m-%d')
day_end = (datetime.datetime.today()-datetime.timedelta(days=2)).strftime('%Y-%m-%d')
day_start = (datetime.datetime.today()-datetime.timedelta(days=9)).strftime('%Y-%m-%d')
####
date = '2014-10-18'
stime = datetime.datetime.strptime(date, '%Y-%m-%d')
etime = stime + datetime.timedelta(days=1)
4.IP与整数的相互转换
def IP2Int(ip):
    o = map(int, ip.split('.'))
    res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
    return res

def Int2IP(ipnum):
    o1 = int(ipnum / 16777216) % 256
    o2 = int(ipnum / 65536) % 256
    o3 = int(ipnum / 256) % 256
    o4 = int(ipnum) % 256
    return '%(o1)s.%(o2)s.%(o3)s.%(o4)s' % locals()
5.Python的内部函数any的使用
if needle.endswith('ly') or needle.endswith('ed') or needle.endswith('ing') or needle.endswith('ers'):
    print('Is valid')
else:
    print('Invalid')
#
if needle in ('ly', 'ed', 'ing', 'ers'):
    print('Is valid')
else:
    print('Invalid')
#
if any([needle.endswith(e) for e in ('ly', 'ed', 'ing', 'ers')]):
    print('Is valid')
else:
    print('Invalid')

上面的代码十分优雅的解决了:检测”一段string是否以特定的字符串结尾?”的问题,给力啊!{参考:Python语言的一小点优雅表现}

6.Python判断字符串是否包含子串的方法

Python的string对象没有contains方法,不能使用string.contains的方法判断某个字符串是否包含某一子串,但是Python有更简单的方法实现该功能。

方法1:使用 in 方法

site = 'http://ixyzero.com/blog/'
if "crazyof" in site:
print('site contains crazyof')
#输出结果:site contains crazyof

方法2:使用 find 函数

s = "This be a string"
if s.find("is") == -1:
print "No 'is' here!"
else:
print "Found 'is' in the string."

方法3:使用 count 函数

s = "This be a string"
if s.count("is") > 0:
print "Found 'is' in the string."
7.判断字符串是否包含子字符串中所有字符的实现(Python)
#!/usr/bin/env python
# -*- coding: utf8 -*-
# Python 2.7.2
"""
问题:假设这有一个由各种字母组成的字符串,假设这还有另外一个字符串,而且这个字符串里的字母数相对少一些。从算法上讲,什么方法能最快的查出所有小字符串里的字母在大字符串里都有?
比如,如果是下面两个字符串:
String a: ABCDEFGHLMNOPQRS
String b: DCGSRQPOM
答案是true,所有在string b里的字母string a也都有。

如果是下面两个字符串:
String a: ABCDEFGHLMNOPQRS
String b: DCGSRQPOZ
答案是false,因为第二个字符串里的Z字母不在第一个字符串里。
"""

def a_has_b(a, b):
    """判断字符串a中是否包含b中的所有字符
    """
    dictionary = 0

    #每个字母的ASCII码值,可以对应一个位图中的位。
    #先遍历第一个字符串,生成一个“位图字典”。
    for a_ch in a:
        dictionary |= (0x01 << (ord(a_ch) - ord('A')))

    #我们遍历第二个字符串,用查字典的方式较检,伪代码为
    for b_ch in b:
        if dictionary != (dictionary |(0x01 << (ord(b_ch) - ord('A')))):
            return False
    return True

#主函数,测试部分
str1="abcdefghijklmnopqrstuvwxyz"
str2="akjsdfasdfiasdflasdfjklffhasdfasdfjklasdfjkasdf"
str3="asdffaxcfsf"
str4="asdfai"
print(a_has_b(str1, str2))
print(a_has_b(str1, str3))
print(a_has_b(str3, str4))
参考链接:
,

发表回复

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