Published 8月 09, 2018 by with 0 comment

習題8 - 打印, 打印




用Notepad++打下列的程式碼,
另存為ex8.py.
formatter = "{} {} {} {}"

print (formatter.format (1,2,3,4))
print (formatter.format ("one", "two", "three", "four"))
print (formatter.format (True, False, False, True))
print (formatter.format (formatter, formatter, formatter, formatter))
print (formatter.format(
    "Try your",
    "Own test here",
    "Maybe a poem",
    "Or a song about fear"
))


然後用Windows的cmd, 執行python打開它.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW

C:\Users\Peter\Desktop\Python\LP3THW>python ./ex8.py
1 2 3 4
one two three four
True False False True
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
Try your Own test here Maybe a poem Or a song about fear

C:\Users\Peter\Desktop\Python\LP3THW>

完成

這次練習主要是學習對字符串做更多複雜的格式化.
我們來修改一下程式碼.
Line 3, 我如果把"2"移除, 只留3個字符,會出現錯誤"IndexError: tuple index out of range".
但如果"2"不移除,反而多加一個"5", 則不會出現錯誤,"5"也不會出現.
Line 4, 主要是將數字與字符串並存.
Line 13 - 14, 主要是學習透過f,做出相同的結果.
formatter = "{} {} {} {}"

print (formatter.format (1,2,3,4,5))
print (formatter.format (1, "two", 3, "four"))
print (formatter.format (True, False, False, True))
print (formatter.format (formatter, formatter, formatter, formatter))
print (formatter.format(
    "Try your",
    "Own test here",
    "Maybe a poem",
    "Or a song about fear"
))
print (f"This is a test {formatter}")
print (f"This is a test {formatter.format (5,6,7,8)}")

結果,
C:\Users\Peter\Desktop\Python\LP3THW>python ./ex8.py
1 2 3 4
1 two 3 four
True False False True
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
Try your Own test here Maybe a poem Or a song about fear
This is a test {} {} {} {}
This is a test 5 6 7 8

C:\Users\Peter\Desktop\Python\LP3THW>

Line 14, 很奇怪只能用數字表示, 不能字符表示, 否則會出現錯誤"SyntaxError: invalid syntax".


最初發表 / 最後更新: 2018.08.09 / 2018.08.09

0 comments:

張貼留言