码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础语法——(引号、字符串)

时间:2017-05-10 01:08:04      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:作用   使用   python   log   变量   处理   last   class   input   

一、单引号字符串和转义引号

  当字符串中出现单引号‘时,我们可以用双引号""将该字符串引起来:"Let‘s go!"

  而当字符串中出现双引号时,我们可以用单引号‘‘将该字符串引起来:‘ "Hello,world!" she said ‘

  但是当字符串中又有单引号‘又有双引号"时该如何处理呢:使用反斜线(\)对字符串中的引号进行转义:‘Let\‘s go!‘

二、字符串

  1. 拼接字符串
>>>"Let‘s say"  ‘ "Hello,world!" ‘
‘Let\‘s say "Hello,world!" ‘
>>>x="hello,"
>>>y="world!"
>>>x y
SyntaxError: invalid syntax
>>>"hello,"+"world!"
‘hello,world!‘
>>>x+y
‘hello,world!‘

   上面只是一个接着一个的方式写了两个字符串,Python就会自动拼接它们,但是如果赋值给变量再用这种方式拼接则会报错,因为这仅仅是书写字符串的一种特殊方法,并不是拼接字符串的一般方法;这种机制用的不多。用"+"好可以进行字符串的拼接;

  2.字符串表示,str和repr

>>>print repr("hello,world!")
‘hello,world!‘
>>>print repr(10000L)
10000L
>>>print str("Hello,world!")
Hello,world!
>>>print str(10000L)
10000

 str和int、bool一样,是一种类型,而repr仅仅是函数,repr(x)也可以写作`x`实现(注意,`是反引号,不是单引号);不过在Python3.0中已经不再使用反引号了。因此,即使在旧的代码中应该坚持使用repr。

  3.input和raw_input的比较

  input会假设用户输入的是合法的Python表达式,比如输入数值1,程序不会当作是str,而是当作int类型,输入x,程序会当作用户输入的是变量x,如果输入"x",程序才会人可是字符串;

  raw_input函数它会把所有的输入当作原始数据,然后将其放入字符串中。

>>> name=input("what is your name ?");print name
what is your name ?Allen

Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    name=input("what is your name ?");print name
  File "<string>", line 1, in <module>
NameError: name ‘Allen‘ is not defined
>>> name=input("what is your name ?");print name
what is your name ?"Allen"
Allen

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

 

Python基础语法——(引号、字符串)

标签:作用   使用   python   log   变量   处理   last   class   input   

原文地址:http://www.cnblogs.com/allen0/p/6833456.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!