西维蜀黍

【Python】前缀

u - Unicode 字符串

Python 中定义一个 Unicode 字符串和定义一个普通字符串一样简单:

>>> u'Hello World !'
u'Hello World !'

引号前小写的"u"表示这里创建的是一个 Unicode 字符串。如果你想加入一个特殊字符,可以使用 Python 的 Unicode-Escape 编码。如下例所示:

>>> u'Hello\u0020World !'
u'Hello World !'

被替换的 \u0020 标识表示在给定位置插入编码值为 0x0020 的 Unicode 字符(空格符)。

其实,\u后面跟四个十六进制数,就可以代表一个Unicode字符。

  ...


【MySQL】MySQL Troubleshooting

Your password has expired.

Description: Your password has expired. To log in you must change it using a client that supports expired passwords.

  ...


【Python】Comprehensions

Comprehensions

要生成list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11))

>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

但如果要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?方法一是循环:

>>> L = []
>>> for x in range(1, 11):
...    L.append(x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

但是循环太繁琐,而列表生成式则可以用一行语句代替循环生成上面的list:

>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来。

for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方:

>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]

还可以使用两层循环,可以生成全排列:

>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
  ...


【Python】I/O - 输入

input()

>>>a = input("input:")
input:123                  # 输入整数
>>> type(a)
<type 'int'>               # 整型
>>> a = input("input:")    
input:"runoob"           # 正确,字符串表达式
>>> type(a)
<type 'str'>             # 字符串
>>> a = input("input:")
input:runoob               # 报错,不是表达式
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'runoob' is not defined
<type 'str'>

raw_input() - 将所有输入作为字符串看待

>>>a = raw_input("input:")
input:123
>>> type(a)
<type 'str'>              # 字符串
>>> a = raw_input("input:")
input:runoob
>>> type(a)
<type 'str'>              # 字符串
>>>
  ...


【Python】Python 一切皆对象

Python的一等公民

Python 中的一等公民,都具有以下特性:

  • 可以赋值给一个变量
  • 可以添加到集合对象中
  • 可以作为参数传递给函数
  • 可以当做函数的返回值

针对赋值给变量及添加到集合对象中,代码予以展示:

def func():
    print 'the func function is executed'


class Test:
    def __init__(self):
        print 'An instance of Test class is initialized'

obj_list = []
obj_list.append(func)
obj_list.append(Test)

for item in obj_list:							# 添加至集合对象中
    print(item())
  ...