Skip to content

Latest commit

 

History

History
100 lines (55 loc) · 3.28 KB

ex08.md

File metadata and controls

100 lines (55 loc) · 3.28 KB

Python基础08(ex08.py)

基本概念

使用类似占位符的百分号(%)来进行输出

Use a placeholder-like percent sign(%)for output

%s 字符串(采用str())

%s string(using str())

%r 字符串(采用repr())

%r string(using repr())

%d 十进制整数

%d decimal integer

使用占位符(%)不仅可以传递变量,也可以直接传递值

Use placeholders(%)to pass not only variables but also values directly

实际练习

#!/usr/bin/env python3
#-*- coding:utf-8 -*-


formatter = '%r %r %r %r' #如果没有传入任何值的情况下,会按照原样输出,如果有传入值的情况下,会输出传入的值。 相对于%s或者%d更直观一些。在没有传入值的情况下也是不会报错的。

print (formatter %(1,2,3,4)) #在这里传入4个值,然后进行输出
print (formatter %("one","two","three","four"))
print (formatter %(True,False,False,True)) # 传入boolean值
# 该语句只会打印出formatter的变量值,在之前的操作并不会影响到这一行的输出,使用%来进行值传递时,不会影响该变量本身。
# This statement will only output the value of the formatter variable The previous operation does not affect the output of the line. When using% to pass a value,it does not affect the variable itself
print (formatter %(formatter,formatter,formatter,formatter))

print (formatter %(
        "I had this thing.",
        "That you could type up right.",
        "but it didn't singa.",
        "So I said goodnight.")
)

#加分题:
#   解释:单引号或双引号,如果使用了单引号开头,那么就需要使用单引号结束。

实际效果:

image-20200403192417699

分析与总结

传递值时一定要确保你传递的值可以正确的被占位符接收(%),如果传递一个字符串给%d则会抛出异常.

When passing a value make sure that the value you pass is correctly received by the placeholder(%).If you pass a string to %d an exception will be thrown

附加练习

练习1注意最后一行程序中既有单引号又有双引号,你觉得它是如何工作的?

简述答案:

使用单引号开头,那么就必须要以单引号结尾.

Use single quotes then you must end with single quotes

在使用双引号或者单引号时都存在字符串作用域的问题

String scoping issues when using double or single quotes

所有在作用域内的字符都会被当成普通的字符串进行处理.

All characters in scope are treated as ordinary strings

脚本

img

结果:

image-20200403192515510

附加笔记

在进行值传递操作时,需要给字符串内所有的占位符都提供传递参数.否则会报错.

When performing a value passing operation you need to provide passing parameters to all placeholders in the string Otherwise an error will be reported

img

image-20200403192540223