python 学习笔记(二) 字符串string和变量variable
1.字符串
类似于之前的代码print("hello world")中,”hello world“这一串字符即为字符串。(包含双引号),
1.1 引号的使用
例子中同样可以把双引号替换为单引号,结果相同。
如果要打印多行字符,则使用三引号,
例如:
print(’’‘this is the first line
this is the second line
last line’’’)
结果为:
this is the first line
this is the second line
last line
1.2 不可变性:字符串一旦被创建就不能改变。
1.3 format字符串(用于输出指定格式的字符串)
例1:
age=3
name=“tom”
print("{0} was {1} years old".format(name,age))
输出: tom was 3 years old
例2:(把不同的字符串用加号连接起来)
age=3
name=“tom”
print(name+“was”+str(age)+“years old”)
输出:tom was 3 years old
其中的name、was"、str(age)、”years old“分别为四个不同的字符串,由于age赋值为3,python自动识别age为数字型变量而非字符串,str的作用就是把其转化为字符串型变量。
2. 常量
常量:不会被改变
2.1字面常量
可以直接以字面的意义使用,如6,2.24,3.45e-3,”this is a string“(字符串的不可变性)
3. 变量
用来储存信息,只是起一个标识的作用,是系统的一个分配空间,用来赋予某个值,属于indentifier。
identifier命名规则:
第一个字符必须是字母或者下划线,其余字符可以是字母、数字、下划线(不能是空格、横杠等),注意区分大小写。
如:
合法:i ; name_3_4 ; big_bang ;
非法:2people ; this is tom ; my-name ; >123b_c2
4.代码注释
使用#,本行范围内#之后的代码将不会被执行。
4.1 #在某行代码最前端时,则此行代码将不被执行如:#print(name+“was”+str(age)+“years old”)
4.2 #在代码的后方,添加中文注释时,#前的代码还是会被执行的。如:*print(name+“was”+str(age)+“years old”) # ************
5. 缩进
python语法结构完全完全建立在缩进的格式上,结尾不需要使用分号区别结构,而是使用分行的方法。