python 学习(一) 字符串、函数

如果脚本中有中文,要在文件头加上如下内容:
# -*- coding: utf-8 -*-
指定默认路径
# /usr/local/python
字符串连接:

print "2+3=",5`  
print "2+3="+str(5)`  
a=2
b=3
c=5
print "%d+%d=%d"%(a,b,c)

%r与%s %r打印变量原始值,不对变量进行任何编解码,适合用于调试
如"hello\nworld" %r 打印hello\nworld

formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)

转义列表

\\ 	Backslash (\)
\' 	Single-quote (')
\" 	Double-quote (")
\a 	ASCII bell (BEL)
\b 	ASCII backspace (BS)
\f 	ASCII formfeed (FF)
\n 	ASCII linefeed (LF)
\N{name} 	Character named name in the Unicode database (Unicode only)
\r 	Carriage Return (CR)
\t 	Horizontal Tab (TAB)
\uxxxx 	Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx 	Character with 32-bit hex value xxxxxxxx (Unicode only)
\v 	ASCII vertical tab (VT)
\ooo 	Character with octal value ooo
\xhh 	Character with hex value hh

非unicode类型的字符串中“\uxxxx”不能直接打印。需要调用相应方法将其转换为unicode类型,如:
print '\u559c'.decode('unicode_escape')
定义为unicode类型即可
print u'\u559c'

字符串输入&类型转换:

print "How old are you?",
age = int(raw_input())

age = int(raw_input("How old are you?"))

字符串换行两种方式:

a="aaaaaaaaa"\
"bbbbbbbb"

a=("aaaaaaaaa"
"bbbbbbbbb")#推荐

与环境交互:

from sys import argv
script, first, second, third = argv
# argv[0]为脚本名
# or
import sys
script, first, second, third = sys.argv
# sys.argv[0]为脚本名

乘幂a=2**7 #a=128

使用r强制不转义

>>> print 'C:\some\name'  # here \n means newline!
C:\some
ame
>>> print r'C:\some\name'  # note the r before the quote
C:\some\name

创建Unicode字符串

a=u"Unicode"

关于字符串索引:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5   
  -6  -5  -4  -3  -2  -1

字符串相关方法

str="ssstttrrr"
len(str) #求长度
# unicode与8进制字符串相互转换
u"盲枚眉".encode('utf-8')
unicode('\xe7\x9b\xb2\xe6\x9e\x9a\xe7\x9c\x89', 'utf-8')

列表操作

squares = [1, 4, 9, 16, 25]
a = ['spam', 'eggs', 100, 1234]
>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

函数定义

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
ask_ok('Do you really want to quit?')
ask_ok('OK to overwrite the file?', 2)
ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
parrot(1000)                                # 1 positional argument
parrot(voltage=1000)                        # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')   # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)   # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')  # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

引入一个形如 **name 的参数时,它接收一个字典(参见 Mapping Types — dict ),该字典包含了所有未出现在形式参数列表中的关键字参数。这里可能还会组合使用一个形如 *name (下一小节详细介绍)的形式参数,它接收一个元组(下一节中会详细介绍),包含了所有没有出现在形式参数列表中的参数值。( *name 必须在 **name 之前出现)


def cheeseshop(kind, *arguments, **keywords):
    print "-- Do you have any", kind, "?"
    print "-- I'm sorry, we're all out of", kind
    for arg in arguments:
        print arg
    print "-" * 40
    keys = sorted(keywords.keys())
    for kw in keys:
        print kw, ":", keywords[kw]

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper='Michael Palin',
           client="John Cleese",
           sketch="Cheese Shop Sketch")

###  输出
--  Do you have any Limburger ?
--  I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

另有一种相反的情况: 当你要传递的参数已经是一个列表,但要调用的函数却接受分开一个个的参数值。这时候你要把已有的列表拆开来。例如内建函数 range() 需要独立的 start ,stop 参数。 你可以在调用函数时加一个 * 操作符来自动把参数列表拆开:

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

以同样的方式,可以使用 ** 操作符分拆关键字参数为字典:

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
--  This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !