Day01 学习笔记

注释与编码声明

  • 文件编码头:# -*- coding: UTF-8 -*-,确保中文可正确显示。
  • 单行注释:以 # 开头。
  • 多行注释:使用三引号 ''' ... '''""" ... """
  • 示例输出中文:print "你好,世界!"

输出与输入

  • 打印:print "hello python!"
  • 不换行打印(Py2):在 print 末尾加逗号:
1
2
print a,
print b,
  • 输入:raw_input("请输入密码:") 会读入字符串。

变量与基本类型

  • 赋值与输出:
1
2
3
4
5
6
money = 2000        # int
count = 1000.0 # float
name = "zhangsan" # str
print money
print count
print name
  • 字符串转整型:int("123")

字符串

索引与切片

  • 基本:s = "hello world!"
    • s[0]'h's[6]'w'
    • 切片左闭右开:s[1:4]'ell's[7:11]'orld'
    • 负索引:s[-5:-1]'orld'
  • 拼接与重复:
    • s * 2s + " TEST"
  • “更新”字符串(生成新串):
    • s[:6] + "python"'hello python'

字符串格式化

  • 百分号格式化:
1
2
"%s,%s,%s。" % (string1, string2, string3)
"更新字符串: %s %s" % (s[:6] + "python", "world")
  • str.format
1
2
3
4
"{},{},{}。".format(string1, string2, string3)
"{0}{1}".format(s[:6], "python")
"{1}{0}".format(s[:6], "python")
"{0}{2}".format(s[:6], "python", "TEST")

常用方法

  • 首字母大写:string1.capitalize()
  • 纯数字判断:string2.isdigit()
  • 去左侧空白:string3.lstrip()
  • 转小写:string4.lower()

成员运算与对齐

  • 成员运算:if "h" in a: 用于子串判断。
  • 百分号拼接示例:print " %sxyz" % "abc"

列表

  • 索引与切片:
1
2
3
4
list1 = ["hello", 'python', 1997, 2000]
list2 = [1,2,3,4,5,6,7]
list1[0] # -> "hello"
list2[3:5] # -> [4, 5]
  • 修改与追加:
1
2
list1[2] = 2018
list1.append("zhangsan")

成员运算与缩进

  • 成员运算:字符串中也可用 in 判断子串是否存在。
  • 缩进:Python 使用缩进表示代码块,同层缩进必须一致。
1
2
3
4
5
6
if True:
print "True"
if True:
print "abc"
else:
print "False"

Day01 学习笔记
https://blog.pangcy.cn/2018/10/13/后端编程相关/python/python2基础/Day01 学习笔记/
作者
子洋
发布于
2018年10月13日
许可协议