Python中的字符串

来源:互联网 发布:k歌之王65首歌名知乎 编辑:程序博客网 时间:2024/06/14 15:33

字符串表示,str和repr

str函数

会把值转换为易于用户理解的字符串:

>>>print str("Hello,world!")Hello,world!>>>print str(1000L)1000

这里长整数1000L被转换为数字1000

repr函数

以合法的Python表达式的形式来表示:

>>>print repr("Hello,world!")'Hello,world!'>>>print repr(1000L)1000L

这里的字符串会以引号括起来的形式打印

input和raw_input

>>> name = input("What is your name?")What is your name?jackTraceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<string>", line 1, in <module>NameError: name 'jack' is not defined

input会假设用户输入的是合法的python表达式

而raw_input可以将输入当做原始数据,然后放入字符串中:

>>> name = raw_input("What is your name?")What is your name?jack>>> print namejack

但是,raw_input只是适于处理字符串的场景,因为不管输入什么,它都会返回一个字符串。
比如想输入数字进行计算,此时就应该使用input

Enter a number:33>>> raw_input("Enter a number:")Enter a number:5'5'

长字符串、原始字符串和Unicode

长字符串

>>> print "This is a very long string  File "<stdin>", line 1    print "This is a very long string                                    ^SyntaxError: EOL while scanning string literal>>> print ''' This is a very long string.... It continues here.''' This is a very long string.It continues here.

可以使用三个单引号或者三个双引号,如”“”Like this”“”。来输入跨行的字符串。

第一行语句,尝试使用一个双引号进行跨行,会报错!

原始字符串

原始字符串对于反斜线并不会特殊对待。

>>> print r"C:\nowhere"C:\nowhere>>> print "C:\nowhere"C:owhere

Unicode字符串

>>> u'Hello'u'Hello'

python3.0中,所有的字符串都是Unicode字符串

原创粉丝点击