3. Python脚本学习笔记三字符串

来源:互联网 发布:迪姆软件 编辑:程序博客网 时间:2024/06/06 18:19

3. Python脚本学习笔记三字符串

                  本篇名言:“平静的湖面只有呆板的倒映,奔腾的激流才有美丽的浪花!幸福不是靠别人来布施,而是要自己去赢取!生命的意义在不断挑战自己,战胜自己!

                  这个本来放在昨天的,由于昨晚又太晚了,所以就搁在这里了。赶紧看看吧。

                  字符串两边都用双引号或者单引号包起来。否则就使用转移符号来转移一下。

输入在一起可以直接拼接。

1.  常用及值转换

>>> 'Let"go '

'Let"go '

>>> "let'go"

"let'go"

>>> "hello world"+"let'sgo"

"hello worldlet's go"

值可以转换为字符串如下示例:

>>> print 1000L

1000

>>> print str(1000L)

1000

>>> print repr(1000L)

1000L

字符串和数值如何合并呢?

这个比较巧妙,要使用反引号

>>> temp=10

>>> print "hello"+`temp`

hello10

当然也可以使用str和repr函数来实现。

>>> print"hello"+str(temp)

hello10

>>> print"hello"+repr(temp)

hello10

所以将值转换为字符串有三种方式:str、repr和反引号。

 

2.  字符串输入

Input和raw_input

不过两者有区别如下:

>>> name=input("what's your name")

what's your nameDavid

Traceback (mostrecent call last):

  File "<stdin>", line 1, in<module>

  File "<string>", line 1, in<module>

NameError: name'David' is not defined

>>> name=raw_input("what's your name")

what's your nameDavid

可以知道input函数需要用户输入的字符串带双引号的。

而raw_input会把所有的输入都当成原始数据,将其放入字符串中。

 

3.  长字符串、转移字符、Unicode字符串

可以使用三个引号替换普通引号。

>>> print '''This is very longggggggggggggggggg

... ggggggggggggggggggggg

... gggg

... string'''

This is very longggggggggggggggggg

ggggggggggggggggggggg

gggg

string

普通字符串要跨行,要加\ 符号。

转义字符 \

例如下

>>> print 'hello ,\n world!'

hello ,

 world!

>>> path='c:\\nowhere'

>>> print path

c:\nowhere

 

关于路径也可以使用r如下:

>>> path=r'c:\nowhere'

>>> print path

c:\nowhere

 

Python中普通字符在内部是8位ASCII码。而Unicode字符串则存储为16位的Unicode字符。

>>> u'Hello,world'

u'Hello,world'

 

 

 

 

 

 

 

 

 

原创粉丝点击