您的位置:首页 > 编程语言 > Python开发

开始Python -- Python基础(2)

2007-10-05 18:05 465 查看
7、String
(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) str和repr函数
l str和repr函数都是将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) input和raw_input
l input和raw_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 String在String前面加“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 g在String前面加“u”:

>>> u'Hello, world!'
u'Hello, world!'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: