您的位置:首页 > 编程语言 > Python开发

(一)《A Byte of Python》 ——基础

2018-01-17 10:32 555 查看
1. 单引号
    指定字符串——所有引号内的空间,诸如空格与制表符,都将按原样保留 。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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: