第一章 基础知识

来源:互联网 发布:lol脚本淘宝怎么不买了 编辑:程序博客网 时间:2024/05/18 03:35

1. 字符串表示,str和repr

>>> "Hello,world!"'Hello,world!'>>> 10000L10000L>>> print "Hello,world!"Hello,world!>>> print 10000L10000>>>
str函数,它会把值转换为合理形式的字符串,以便用户可以理解
>>> print str("Hello,world!")Hello,world!>>> print str(10000L)10000>>> 
repr函数会创建一个字符串,它以合法的Python表达式的形式来表示值。repr(x)的功能也可以用`x`实现(反单引号)
>>> print repr("Hello,world!")'Hello,world!'>>> print repr(10000L)10000L>>> 
str、repr和反单引号(python3.0中已经不再使用反单引号)是将Python值转换为字符串的3种方法。


2. input和raw_input的比较

>>> name=input("What is your name? ")What is your name? GumbyTraceback (most recent call last):  File "<pyshell#49>", line 1, in <module>    name=input("What is your name? ")  File "<string>", line 1, in <module>NameError: name 'Gumby' is not defined>>> >>> name=input("What is your name? ")What is your name? "Gumby">>>>>> print "Hello, " + name + "!"Hello, Gumby!>>> 
问题在于input会假设用户输入的是合法的Python表达式;
>>> input("Enter a number: ")Enter a number: 33>>> >>> raw_input("Enter a number: ")Enter a number: 3'3'
raw_input函数会把所有的输入当作原始数据(raw data),然后将其放入字符串中;
除非对input有特别要求,否则应尽可能将其放入字符串中;