python学习笔记(三)之变量和字符串

  在其他语言中,变量就是有名字的存储区,可以将值存储在变量中,也即内存中。在Python中略有不同,python并不是将值存储在变量中,更像是把名字贴在值上边。所以,有些python程序员会说python没有变量,只有名字。

 简单实践:

 1 >>>teacher = 'zengan'
 2 >>>print(teacher)
 3 >>>teacher = 'pandan' 
 4 >>>print(teacher) 
 5 >>>first = 3
 6 >>>second = 8
 7 >>>third = first + second
 8 >>>print(third) 
 9 >>>myteacher = 'zengan'
10 >>>yourteacher = 'zengbi'
11 >>>ourteacher = myteacher + yourteacher
12 >>>print(ourteacher)
View Code

需要注意的地方:

  1.  在使用变量之前,要对其先赋值
  2.  变量名可以包括数字,字母,下划线,但变量名不能以数字开头
  3.  python中大小写敏感,temp和Temp是两个不同的变量
  4.  等号(=)是赋值
  5.  特别重要的一点是,注意变量的命名,给变量起一个合适的名字,哪怕需要好好想一想。

 字符串

  可以用单引号或双引号,但是必须成对出现。利用转义字符可以打印单引号或双引号。

1 >>>print('Hello Python')
2 >>>print("Hello Python")
3 >>>print("Hello Python') #SyntaxError
View Code

  在Python中,#表示单行注释的开始,可以将需要注释的多行内容,放在三个单引号或双引号之间,如‘’‘注释内容’‘’或“”“注释内容”“”

原始字符串:

  由于转义字符的存在,打印一个字符串,可能会出现出人意料的错误,如:

1 >>>path = "C:
ow"
2 >>>print(path)
3 >>> print(path)
4 C:
5 ow
View Code

  出现了意外的结果,这时候使用原始字符串,可以去掉字符串中特色字符的含义,还原其本来意思。原始字符串就是在字符串前加一个小写的r。

1 >>>path = r"C:
ow"
2 >>> print(path)
3 C:
ow
View Code

长字符串:

  如果希望得到一个跨越多行的字符串,例如

1 I love three things:the sun ,the moon and you.
2 the sun is for the day ,the moon is for the night
3 and you forever.
View Code

  这时候就需要三重引号字符串了。

 1 >>> poet = """I love three things:the sun ,the moon and you.
 2 ... the sun is for the day ,the moon is for the night
 3 ... and you forever.
 4 ... """
 5 >>> print(poet)
 6 I love three things:the sun ,the moon and you.
 7 the sun is for the day ,the moon is for the night
 8 and you forever.
 9 >>> poet = '''I love three things:the sun ,the moon and you.
10 ... the sun is for the day ,the moon is for the night
11 ... and you forever.
12 ... '''
13 >>> print(poet)
14 I love three things:the sun ,the moon and you.
15 the sun is for the day ,the moon is for the night
16 and you forever.
View Code

    

  

原文地址:https://www.cnblogs.com/ZGreMount/p/7756886.html