开始Python -- Python基础(2)

7String

1) 字符串引号和转义字符

l         String可以用单引号或双引号包含,其中使用到引号,可以用“/”转义:

>>> 'Let/'s go!'

"Let's go!"

>>> "/"Hello, world!/" she said"

'"Hello, world!" she said'

l         注意,输出都用引号包含,因为是String对象;而print语句输出String值,没有引号:

>>> print 'Let/'s go!'

Let's go!

2 String连接:+

>>> x = "Hello, "

>>> y = "world!"

>>> x + y

'Hello, world!'

3 strrepr函数

l         strrepr函数都是将Python值转换成String;两者的区别:str是简单的将值转换成String,而repr是创建一个String来表示合法的Python表达式值:

>>> repr("Hello, world!")

"'Hello, world!'"

>>> str("Hello, world!")

'Hello, world!'

>>> repr( 10000L )

' 10000L '

>>> str( 10000L )

'10000'

l         repr(x)的简化形式是`x `:

>>> temp = 42

>>> print "The temperature is " + `temp`

The temperature is 42

4 inputraw_input

l         inputraw_input的区别:input认为输入的是合法的Python表达式;而raw_input将所有的输入内容作为RAW数据,会转换成String

l         假设下面的脚本保存到hello.py中:

name = input("What is your name? ")

print "Hello, " + name + "!"

l         执行python hello.py

What is your name? Gumby

Traceback (most recent call last):

File "C:/hello.py", line 2, in ?

name = input("What is your name? ")

File "<string>", line 0, in ?

NameError: name 'Gumby' is not defined

l         这里出错是因为Python认为Gumby是一个变量,而不是String;使用raw_input替换input,就能得到正确的结果:

What is your name? Gumby

Hello, Gumby!

5) 长String

l         String可以包含换行符,包括数行文字,用“'''”包括起来:

>>> print '''This is a very long string.

... It continues here.

... And it's not over yet.

... And it's not over yet.

... "Hello, world!"

... Still here.'''

This is a very long string.

It continues here.

And it's not over yet.

And it's not over yet.

"Hello, world!"

Still here.

l         或者在行尾加“/:

>>> print "Hello, /

... world!"

Hello, world!

6 RAW String

l         看下面的例子:

>>> path = 'C:/nowhere'

>>> print path

C:

owhere

l         为了得到想要的结果,需要进行转移:

>>> path = 'C://nowhere'

>>> print path

C:/nowhere

l         RAW String将内容作为普通字符处理,RAW StringString前面加“r”:

>>> path = r'C:/nowhere'

>>> print path

C:/nowhere

l         RAW String的结尾不能为“/:

>>> print r"This is illegal/"

Traceback (  File "<interactive input>", line 1

    print r"This is illegal/"

                            ^

SyntaxError: EOL while scanning single-quoted string

l         可以这样处理:

>>> print r"This is legal" + "//"

This is legal/

7 Unicode String

l         Unicode String gString前面加“u”:

>>> u'Hello, world!'

u'Hello, world!'

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值