初識 Python:Hello World 和字串操作

Michael發表於2018-03-21

開始之前,說一下本文中的程式碼視訊可以在我的 GitHub 上找到。

那麼,讓我們開始吧!如果你糊塗了,我建議你在單獨的選項卡中開啟下面的視訊。

開始 (先決條件)

首先在你的作業系統上安裝 Anaconda (Python)。你可以從官方網站下載 anaconda 並自行安裝,或者你可以按照以下這些 anaconda 安裝教程進行安裝。

  • 在 Windows 上安裝 Anaconda: [連結5
  • 在 Mac 上安裝 Anaconda: 連結
  • 在 Ubuntu (Linux) 上安裝 Anaconda:連結

開啟一個 Jupyter Notebook

開啟你的終端(Mac)或命令列,並輸入以下內容(請參考視訊中的 1:16 處)來開啟 Jupyter Notebook:

jupyter notebook

列印語句/Hello World

在 Jupyter 的單元格中輸入以下內容並按下 shift + 回車來執行程式碼。

# This is a one line comment
print('Hello World!')

列印輸出 “Hello World!”

字串和字串操作

字串是 Python 類的一種特殊型別。作為物件,在類中,你可以使用 .methodName() 來呼叫字串物件的方法。字串類在 Python 中預設是可用的,所以你不需要 import 語句來使用字串物件介面。

# Create a variable
# Variables are used to store information to be referenced
# and manipulated in a computer program.
firstVariable = 'Hello World'
print(firstVariable)

輸出列印變數 firstVariable

# Explore what various string methods
print(firstVariable.lower())
print(firstVariable.upper())
print(firstVariable.title())

使用 .lower()、.upper() 和 title() 方法輸出

# Use the split method to convert your string into a list
print(firstVariable.split(' '))

使用 split 方法輸出(此例中以空格分隔)

# You can add strings together.
a = "Fizz" + "Buzz"
print(a)

字串連線

查詢方法的功能

對於新程式設計師,他們經常問你如何知道每種方法的功能。Python 提供了兩種方法來實現。

1、(在不在 Jupyter Notebook 中都可用)使用 help 查詢每個方法的功能。

查詢每個方法的功能

2.(Jupyter Notebook 專用)你也可以通過在方法之後新增問號來查詢方法的功能。

# To look up what each method does in jupyter (doesnt work outside of jupyter)
firstVariable.lower?

在 Jupyter 中查詢每個方法的功能

結束語

如果你對本文或在 YouTube 視訊的評論部分有任何疑問,請告訴我們。文章中的程式碼也可以在我的 GitHub 上找到。本系列教程的第 2 部分是簡單的數學操作


via: https://www.codementor.io/mgalarny/python-hello-world-and-string-manipulation-gdgwd8ymp

作者:Michael 譯者:geekpi 校對:wxy

本文由 LCTT 原創編譯,Linux中國 榮譽推出

相關文章