(一)《A Byte of Python》 ——基础
2018-01-17 10:32
555 查看
1. 单引号
指定字符串——所有引号内的空间,诸如空格与制表符,都将按原样保留 。e.g.:'Hello world!'
2. 双引号
与单引号作用相同。e.g.:“Hello World!”
3. 三引号
使用三个引号——"""或'''来指定多行字符串
4. 格式化方法
从其他信息中构建字符串——format()
输出:Python从 0开始计数
Python 中format方法所做的事情便是将每个参数值替换至格式所在的位置。
print总是会以一个不可见的“新一行”字符(\n)结尾,因此重复调用print将会在相互独立的一行中分别打印。为防止
打印过程中出现这一换行符。可以通过end指定其应以空白结尾。
通过end 指定以空格结尾:
5. 转义序列
'What\'s your name?' =“What's your name?”
"This is the first sentence. \
This is the second sentence."
相当于"This is the first sentence. This is the second sentence."
通过使用反斜杠将其拆分成多个物理行,被称作显式行连接 。
6. 原始字符串
所有字符串都是直接按照字面意思来使用,没有转义特殊或者不能打印的字符。
e.g.:r”=\n” 就是包含”\” 和 =“n” 的两个字符,而 “\n” 则是一个字符,表示一个换行。
系统会对\t和\r进行错误的识别,在文件名路径前加上r之后:
指定字符串——所有引号内的空间,诸如空格与制表符,都将按原样保留 。e.g.:'Hello world!'
2. 双引号
与单引号作用相同。e.g.:“Hello World!”
3. 三引号
使用三个引号——"""或'''来指定多行字符串
'''这是一段多行字符串。这是它的第一行。 This is the second line. "How old are you?" "22" '''
4. 格式化方法
从其他信息中构建字符串——format()
age = 4 name = 'Bob' print('{0} was {1} years old when he broke the cup'.format(name, age)) print('Why is {0} playing with that python?'.format(name))
输出:Python从 0开始计数
$ python str_format.py Bob was 20 years old when he broke the cup Why is Bob playing with that python?
Python 中format方法所做的事情便是将每个参数值替换至格式所在的位置。
# 对于浮点数 '0.333' 保留小数点(.)后三位 print('{0:.3f}'.format(1.0/3)) # 使用下划线填充文本,并保持文字处于中间位置 # 使用 (^) 定义 '___hello___'字符串长度为 11 print('{0:_^11}'.format('hello'))
print总是会以一个不可见的“新一行”字符(\n)结尾,因此重复调用print将会在相互独立的一行中分别打印。为防止
打印过程中出现这一换行符。可以通过end指定其应以空白结尾。
print('a', end='') print('b', end='') 输出:ab
通过end 指定以空格结尾:
print('a', end=' ') 输出:a b c print('b', end=' ') print('c')
5. 转义序列
'What\'s your name?' =“What's your name?”
"This is the first sentence. \
This is the second sentence."
相当于"This is the first sentence. This is the second sentence."
通过使用反斜杠将其拆分成多个物理行,被称作显式行连接 。
6. 原始字符串
所有字符串都是直接按照字面意思来使用,没有转义特殊或者不能打印的字符。
e.g.:r”=\n” 就是包含”\” 和 =“n” 的两个字符,而 “\n” 则是一个字符,表示一个换行。
>>> f = open("D:\windows\temp\readme.txt",'r') Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> f = open("D:\windows\temp\readme.txt",'r') IOError: [Errno 22] invalid mode ('r') or filename: 'D:\\windows\temp\readme.txt'
系统会对\t和\r进行错误的识别,在文件名路径前加上r之后:
>>> f = open(r"D:\windows\temp\readme.txt",'r') >>> f.readline() 'Hello World!' >>> f.close()
相关文章推荐
- Python 学习笔记: A byte of python (一) 基础
- 【byte-of-python 学习笔记】——基础知识
- 【A ByteOf Python2.7】第10章 解决问题——编写一个Python脚本
- A Byte of Python -- Functions
- A Byte of Python(简明Python教程) for Python 3.0 下载
- a byte of python3 中文
- A Byte of Python 笔记(7)数据结构:列表、元组、字典,序列
- Byte-of-python笔记代码1:helloworld.py
- 【A ByteOf Python2.7】第12章 输入/输出
- Byte of Python学习笔记八
- A_Byte_Of_Python_1
- OK - A byte of python - 读书笔记
- A Byte of Python 笔记(6)模块
- A Byte of Python 简明Python教程 读书笔记
- A Byte of Python 笔记(9) 面向对象编程
- Byte-of-python笔记代码2:module.py
- 学习python-a byte of python-exception
- a byte of python
- a byte of python初学笔记 001
- A Byte of Python (for Python 3.0) 下载