python学习1

一基础:
1.1字符串拼接
“Hello” + “ world!” =》 “Hello world!”
x = “Hello”, y = “ world!”
x + y =》 “Hello world!”

1.2字符串表示(str和repr):
使用python直接输出的字符串是用单引号表示的python类型值:
“Hello world!” =》 ‘Hello world!’//表示该对象未字符串对象
1000L =》 1000L//表示该值为长整型

使用print函数输出字符串可以得到字符串值
print “Hello world!” =》Hello world!
print 1000L =》 1000

1.2.1str类型
如:print str("Hello world!") => Hello World!
print  str(1000L) => 1000L

str([object])

返回一个可以用来表示对象的可打印的友好的字符串

    对字符串,返回本身。
    没有参数,则返回空字符串

    对类,可通过 __str__() 成员控制其行为。该成员不存在,则使用其 __repr__() 成员。

与 repr 区别:不总是尝试生成一个传给 eval 的字符串,其目标是可打印字符串。

Python 手册:

    Return a string containing a nicely printable representation of an object. For strings, this returns the

string itself. The difference with repr(object) is that str(object) does not always attempt to return a

string that is acceptable to eval(); its goal is to return a printable string. If no argument is given,

returns the empty string, .


1.2.2repr函数
如:print repr(“Hello world!”) =》 ‘Hello world!’
print repr(1000L) =》 1000L


repr(object)

返回一个可以用来表示对象的可打印字符串

    首先,尝试生成这样一个字符串,将其传给 eval()可重新生成同样的对象
    否则,生成用尖括号包住的字符串,包含类型名和额外的信息(比如地址)

    一个类(class)可以通过 __repr__() 成员来控制repr()函数作用在其实例上时的行为。

Python 手册:

    Return a string containing a printable representation of an object. This is the same value yielded by

conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary

function. For many types, this function makes an attempt to return a string that would yield an object

with the same value when passed to eval(), otherwise the representation is a string enclosed in angle

brackets that contains the name of the type of the object together with additional information often

including the name and address of the object. A class can control what this function returns for its

instances by defining a repr() method.

注:str和repr都是转换为字符串,str是友好的,repr则是表示python类型的字符串。str是类型,repr是

函数。

1.3 input和raw_input
input([prompt])
等同于 eval(raw_input(prompt)).
注意:input的输入要求是一个有效的python表达式.
如:
input(“Name :”)
如果再Name :后直接输入字符串内容 Tom是错误的。因为它不是有效的python表达式。
应该输入“Tom”

但是使用raw_input()则不会有此问题,它会将输入当做原始数据放入字符串中。
如:raw_input("Number :")
Number : 13 =>'13'//表示字符串13

1.4 字符串换行
如果需要很长的字符串(或表达式),可以使用\换行。
对于长字符串可以使用三个单引号('''......'''),或三个双引号("""......""")表示,而不用使用\换行,并

且长字符串中的单引号或双引号字符不用再转义。

1.5 原始字符串
以r开头的字符串为原始字符串,如:r‘Hello world!’
注意:原始字符串中的任何字符都会保持原始字符形式,不会处理转义字符。
          如 print r‘Hello \nworld’  =》Hello \nworld
          原始字符串不能已反斜杠\结尾,如果要结尾输出反斜杠,则以字符串拼接实现,+‘\\’。

1.6 unicode字符串
python3.0中字符串都为unicode字符串,以u开头。
u‘Hello World!’ =》u‘Hello World!’
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值