关闭

开始Python -- Python基础(2)

标签: pythonstringinputpathfilego
1295人阅读 评论(0) 收藏 举报
分类:

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!'

 

 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:67280次
    • 积分:989
    • 等级:
    • 排名:千里之外
    • 原创:30篇
    • 转载:1篇
    • 译文:0篇
    • 评论:12条
    文章分类
    最新评论
    Cracks
    Drupal
    Framework
    Groovy
    Jabber/XMMP
    Template
    友情链接