Mes
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
###### tags: `Python` # 字串與Format **<a href="https://hackmd.io/@Mes/python_note" class="redlink">點此回到 Python筆記 目錄</a>** # ## 字串 String 上次提到了四種基本的型態,但有一種還沒有講到,那就是 String字串。 字串如字面上的意思就是一段文字,通常會是英文,但在不同的編碼方式下也可以擁有不同的語言,像是 Unicode 又被稱為萬國碼,因為它為每個語言都設定了二進制編碼,所以什麼文字都可以使用。 那我們該如何使用String呢? 我們一樣需要創一個變數: ```python= s = "hello world" print(s) ``` 字串的內容前後需要有 `""` 或 `''` ,雙引號或單引號把他包起來,引號內就是字串的內容。上面例子中, s 這個變數儲存了 hello world 這段文字,所以 s 的型態就是 String 。 之後我們使用了 print 這個函式將 s 給打印出來,因此我們可以在終端機看到它顯示了 hello world 。 那假如我們想要把兩個字串接在一起該怎麼做呢? 這時候我們可以用 + 這個符號來達成目的: ```python= a = "hello " b = "world" print(a+b) ``` 上例中我們利用 + 這個符號將「變數a」和「變數b」接起來的結果給打印出來,因此我們可以在終端機上看見 hello world 。 要注意的是,如果我們的目的是將字串接起來,那 + 號前後理所當然的都要是 String ,那我們可以試試看如果前後有其他型態的變數會發生什麼事: ```python= s = "hello " n = 123 print(s+n) ``` 上例中「變數s」的型態是 String,而「變數n」的型態則是 int,當我們執行這個程式,會發現噴了一個錯,叫做TypeError,並且註釋寫了 "can only concatenate str(not "int") to str",這段文字的意思是「我們只能將字串與字串接在一起,不能是整數」,那為什麼會這樣呢? 其原因是程式是從左邊讀到右邊的,當今天它讀到 `print(s+n)` 的時候,會先讀到「變數s」,然後再讀到 + 號,於是這時直譯器就認為我們是要開始連接字串了,然後接下來它卻讀到了一個整數,於是便噴錯了。 那們如果我們將 print 內「變數s」與「變數n」的順序對調會發生什麼呢? 可以試試看: ```python= s = "hello " n = 123 print(n+s) ``` 執行後一樣噴了錯,而名稱雖然相同,但註釋卻不一樣了! 這次的註釋寫著 " unsupported operand type(s) for +: 'int' and 'str' ",這段文字簡單來說,意思是「我們無法將整數與字串相加」。 讀到這裡,敏銳一點的人可能會發現,上面兩個例子,明明同樣都是 + 號,但實際做的事情卻不一樣耶! 這是當系統看見 + 這個符號時,要做什麼事是由人定義出來的,以上方兩個例子來說,如果看見一個整數後面有 + 號,那就做「加法」,而如果是一個字串後面有 + 號,那就做「字串連接」。 這樣同樣一個符號卻有不同的行為,就叫做「運算子重載」。 <br> 再來回到字串,如果我們想將同一個字串重複很多次,例如 "hahahahaha" 就是 "ha" 重複了五次的結果,那我們可以使用 * 號來達到目的: ```python= s = "ha" print(s*5) ``` 如此一來不用重複打五次 ha 便可以印出 hahahahaha 了 <br> ## Format ### 傳統的Format 那假設我們要印出一個像是 HololiveEN組的訂閱數 這類簡單的列表: ```pyhton= ina_name = "Ninomae Ina'nis" ina_sub = "76.8萬" ame_name = "Watson Amelia" ame_sub = "97.3萬" gura_name = "Gawr Gura" gura_sub = "215萬" kiara_name = "Takanashi Kiara" kiara_sub = "77.1萬" calli_name = "Mori Calliope" calli_sub = "105萬" print(ina_name + " :" + ina_sub) print(ame_name + " :" + ame_sub) print(gura_name + " :" + gura_sub) print(kiara_name + " :" + kiara_sub) print(calli_name + " :" + calli_sub) ``` 輸出結果: ```python= Ninomae Ina'nis :76.8萬 Watson Amelia :97.3萬 Gawr Gura :215萬 Takanashi Kiara :77.1萬 Mori Calliope :105萬 ``` 在上例中,由於每位 Vtuber 的名字長度不同,我們為了對齊冒號,就在冒號前面加了很多空格來達成目的。 但這樣十分麻煩,還要一格一格空白鍵去按,因此,Python 就有一個功能叫做 「Format」,它通常會搭配 print 來使用,畢竟是要控制輸出的格式嘛: ```python= ina_name = "Ninomae Ina'nis" ina_sub = "76.8萬" ame_name = "Watson Amelia" ame_sub = "97.3萬" gura_name = "Gawr Gura" gura_sub = "215萬" kiara_name = "Takanashi Kiara" kiara_sub = "77.1萬" calli_name = "Mori Calliope" calli_sub = "105萬" print("{} {:>1} {}".format(ina_name, ":", ina_sub)) print("{} {:>3} {}".format(ame_name, ":", ame_sub)) print("{} {:>7} {}".format(gura_name, ":", gura_sub)) print("{} {:>1} {}".format(kiara_name, ":", kiara_sub)) print("{} {:>3} {}".format(calli_name, ":", calli_sub)) ``` format 的語法是 `"{ }".format()` , `{ }` 內會填入我們想要的格式,若要格式化就需要有冒號,反之則可以留白 ; 後方 format括號 內會填入要套用這個格式的字串。 第一個 `{ }` 內套用的格式會對應到後方 format括號 內的第一個參數,第二個 `{ }` 對應到第二個參數,以此類推。 上面這個例子中,第一個參數(名字) 與 第三個參數(訂閱數) 都不需要套用輸出格式,只有 第二個參數(冒號) 需要對齊。上方`{ }` 內 `>` 這個符號的意思是向右對齊,同樣可以使用 `<` 來向左對齊。 ### Fstring 那你可能會覺得它寫起來好麻煩呀,語法怎麼看起來這麼複雜? 欸沒錯,大家都這樣覺得,於是 「Fstring」 就出現了,利用 Fstring,上方的例子可以改成: ```python= ina_name = "Ninomae Ina'nis" ina_sub = "76.8萬" ame_name = "Watson Amelia" ame_sub = "97.3萬" gura_name = "Gawr Gura" gura_sub = "215萬" kiara_name = "Takanashi Kiara" kiara_sub = "77.1萬" calli_name = "Mori Calliope" calli_sub = "105萬" print(f"{ina_name} {':':>1} {ina_sub}") print(f"{ame_name} {':':>3} {ame_sub}") print(f"{gura_name} {':':>7} {gura_sub}") print(f"{kiara_name} {':':>1} {kiara_sub}") print(f"{calli_name} {':':>3} {calli_sub}") ``` 要注意的是 Fstring 是 Python3.6 後才有的東西,在使用的時候要注意一下自己 Python 的版本是多少。 Fstring 的語法是 `f"{要替換的東西:要套用的格式}"` ,以上例這行 `print(f"{ina_name} {':':>1} {ina_sub}")` 來講,第一個 `{ina_name}` 會被替換為 `Ninomae Ina'nis` ,並不套用任何格式, `{':':>1}` 則是將 ':' 這個字串向右靠齊一格。 在使用時要注意的是若要在 `f" "` 的內容內再新增字串,像是上方的 `':'` 一樣,要記得跟最外面的引號不同,在上例中我最外層是使用雙引號,因此在內部的冒號兩側便使用了單引號。 另外,使用 fstring 在執行速度上會比傳統的 format 還來的快,詳細可以看這篇: [探索Python F-strings是如何工作](https://kknews.cc/zh-tw/code/vzmvx22.html) <br> # 練習 ### 練習1 : 自己建立一個表格,並將他們對齊 > 你可以自己找一些資料來實作,也可以直接利用上面例題的內容來做 <br> # 額外文章 那今天這篇就到這裡告一段落了,看到這裡你可能會想說,阿所以這些可以幹嘛,怎麼看起來那麼爛... ![](https://i.imgur.com/xzn7ik0.jpg) 欸對我就爛,不是啦,在未來寫程式時,一定會需要 Debug,那時候就會需要字串的處理了,又或是在做一些終端機的小遊戲之類的時,字串也是個很重要的東西。 那實際上還有更多的函式與運算符可以運用,大家可以多看看別的文章: **<a href = "https://chunyeung.medium.com/%E7%B5%A6%E8%87%AA%E5%AD%B8%E8%80%85%E7%9A%84python%E6%95%99%E5%AD%B8-7-%E5%AD%97%E4%B8%B2-string-1fa93a9aa471" class = "redlink">給自學者的Python教學(7):字串(String)</a>** **<a href = "https://blog.csdn.net/jpch89/article/details/84099277?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control" class = "redlink">Python 中str.format() 方法詳解</a>** **<a href = "https://blog.csdn.net/sunxb10/article/details/81036693" class = "redlink">Python格式化字符串f-string概覽</a>** <style> .green { color:#29E5A9; } .brown { color:#990000; } .pink { color:#C18387; } .red { color:#E71B18 ; } .blue { color:#0b5394; } .purple { color:#AC9FDD; } @-webkit-keyframes A { 0% { color:#C10066;} 10% { color: #CC0000;} 20% { color: #E63F00; } 30% { color:#EE7700; } 40% { color: #DDAA00; } 50% { color:#EEEE00;} 60% { color: #99DD00;} 70% { color:#66DD00;} 80% { color: #00DDDD;} 90% { color: #0044BB;} 100% { color: #A500CC;} } #animation_title{ animation: A 3s ease 0s infinite alternate; -webkit-animation: A 3s ease 0s infinite alternate; } </style> <style> a.redlink { color:#DF2F6A; } a.redlink:link { color:#DF2F6A; text-decoration:none; } a.redlink:visiteid { color:#DF2F6A; text-decoration:none; } a.redlink:hover { color:#19CABC; text-decoration:none; } a.redlink:active { color:#000000; text-decoration:underline; background:#FFFFFF; } </style> <style type="text/css"> h1 { font-size:; color:#0b5394; } h2 { font-size:; color:#0b5394; } p { font-size:; color:; } h3 { font-size: ; color:#990000; } h4 { font-size:; color:#990000; } </style>

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully