10分钟学会Python[1]
2008-10-23 13:27:13 来源:WEB开发网字符串可以使用单引号或者双引号,你可以在使用一个引号的里面嵌套使用另一种引号(也就是说,"He said 'hello'."是合法的)。多行字符串则使用三引号(单双皆可)。Python还可以让你设置Unicode编码,语法如下:u"This is a unicode string".使用值填充一个字符串的时候可以使用%(取模运算符)和一个元组。每个%s使用元组中的一个元素替换,从左到右。你还可以使用字典。如下所示:
>>>print "Name: %snNumber: %snString: %s" % (myclass.name, 3, 3 * "-")
6. 流程控制
Name: Poromenos
Number: 3
String: ---
strString = """This is
a multiline
string."""
# WARNING: Watch out for the trailing s in "%(key)s".
>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}
This is a test.
流程控制使用while,if,以及for。没有select[和哪种语言对比?不知道。译注],使用if代替。使用for来列举列表中的元素。要得到一个数字的列表,可以使用range(<number>)。这些声明的语法如下:
rangelist = range(10)
7. 函数
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in rangelist:
# Check if number is one of
# the numbers in the tuple.
if number in (3, 4, 7, 9):
# "Break" terminates a for without
# executing the "else" clause.
break
else:
# "Continue" starts the next iteration
# of the loop. It's rather useless here,
# as it's the last statement of the loop.
continue
else:
# The "else" clause is optional and is
# executed only if the loop didn't "break".
pass # Do nothing
if rangelist[1] == 2:
print "The second item (lists are 0-based) is 2"
elif rangelist[1] == 3:
print "The second item (lists are 0-based) is 3"
else:
print "Dunno"
while rangelist[1] == 1:
pass
更多精彩
赞助商链接