Beginning Python 笔记学API —— Chapter1 字符串

1、单引号字符串和转义引用

双引号或单引号字符串里面可以包含另外一种符号,不需要转义,否则用\转义。

 

2、拼接字符串

挨着写两个字符串会自动连接 【只限于字符串本身,变量不行】

加法运算可以用于拼接字符串

 

3、字符串表示str和repr

使用str,python会把值转换成合理形式的字符串,以便用户可以理解;

而repr会创建一个字符串,它以合法的python表达式形式来表示值。【区别就在于表达式】

 

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

 

repr(x)的功能也可以用来实现`X`(反引号),如果希望打印一个包含数字的语句,反引号就比较有用额,但3.0已经不支持了,可以用repr代替

 

>>> temp = 42
>>> print "The temperature is " + temp

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    print "The temperature is " + temp
TypeError: cannot concatenate 'str' and 'int' objects
>>> print "The temperature is " + `temp`
The temperature is 42

 

4、input和raw_input对比

input 会【假设】用户输入的事合法的Python表达式。

而raw_input会把所有的输入当做原始数据(raw data),然后将其放入字符串中:

 

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

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    name = input("What is your name?")
  File "<string>", line 1, in <module>
NameError: name 'jason' is not defined

 

>>> input("Enter a number:")
Enter a number:3
3
>>> raw_input("Enter a number:")
Enter a number:3
'3'

 

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

》长字符串:    

’‘’ ** ‘’‘ 可以跨行,不需要转义其中引号

》原始字符串:

对于路径的情况,往往需要将所有的\换成\\,这样需要复制之后做很多添加,原始字符串可以解决这个问题

>>> print 'F:\python\npython\Doc'
F:\python
python\Doc
>>> print r'F:\python\npython\Doc'
F:\python\npython\Doc
 》Unicode字符串:

Python中的普通字符串在内部是以8位ASCII码形成存储的。

>>> temp = ['temp1','temp2']
>>> print temp
['temp1', 'temp2']
>>> temp = [u'temp1',u'temp2']
>>> print temp
[u'temp1', u'temp2']

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值