Python學習筆記 - 字串,數字

MADAO是不會開花的發表於2018-12-11

1. 字串

在Python中,用引號包起來的都是字串。

  • 引號

字串的引號必須開頭和結尾一樣,也就是說雙引號(")開頭的字串,必須以雙引號結尾,單引號(')開頭的字串,必須以雙單號結尾,雙引號中可以包含單引號,同樣單引號中可以包含雙引號。例子:

sentence = 'Love is a touch and yet not a touch."——Jerome David Salinger"'
print(sentence)

sentence = "Love is a touch and yet not a touch.'——Jerome David Salinger'"
print(sentence)
複製程式碼

Python學習筆記 - 字串,數字

  • 拼接
print('cat' + 'dog')
複製程式碼

Python學習筆記 - 字串,數字

  • 重複

在Python中可以用*來重複。例子:

print('cat' * 20)
複製程式碼

Python學習筆記 - 字串,數字

但是不能這樣:

print('cat' + 5)
複製程式碼

Python學習筆記 - 字串,數字

  • 字串的大小寫

Python中提供了title(),lower(),upper()這幾內建函式來改變字串的大小寫,例子:

name = 'allen walker'
print(name.title())
print(name.lower())
print(name.upper())
複製程式碼

Python學習筆記 - 字串,數字

title會讓字串中的單詞首字母大寫,lower就是全部小寫,upper為全部大寫

  • 換行符和製表符

Python中可以使用\n和\t代表換行符和製表符,例子:

print('hobby:\ngakki\nanime\nsleep')
print('hobby:\n\tgakki\n\tanime\n\tsleep')
複製程式碼

Python學習筆記 - 字串,數字

  • 刪除空白

Python中提供了strip(),lstrip(),rstrip()來刪除字串中的空白:

  • strip可以將字串兩端的空白刪除。

  • lstrip可以字串左端的空白刪除。

  • rstrip可以字串右端的空白刪除。

    language = '  Python      '
    language1 = '  JavaScript      '
    language2 = '  Java      '
    print(language.strip())
    print(language1.lstrip())
    print(language2.rstrip())
    複製程式碼

    Python學習筆記 - 字串,數字

  • 長字串

Python中過長的字串可以用"""或者'''來包裹,例子:

long_string = """Grasshoppers are insects in the suborder Caelifera, probably
the oldest living group of chewing herbivorous insects, dating back to the
early Triassic around 250 million years ago. They are typically
ground-dwelling insects with powerful hind legs which enable the"""

long_string1 = '''\n\nGrasshoppers are insects in the suborder Caelifera, probably
the oldest living group of chewing herbivorous insects, dating back to the
early Triassic around 250 million years ago. They are typically
ground-dwelling insects with powerful hind legs which enable the'''

print(long_string, long_string1)
複製程式碼

Python學習筆記 - 字串,數字

2. 數字

Python中數字型別分為整數和浮點數,浮點數就是帶小數點的數字。 可以使用 加(+)、減(-)、乘(*)、除(/)進行運算。除了這4種,Python種還可以進行指數(**)和 取餘(%)運算。例子:

Python學習筆記 - 字串,數字

其中 3**5就是3的5次冪。

需要注意的一點,Python3中整除需要使用 // 操作符。例子:

Python學習筆記 - 字串,數字

當一個數特別大的時候Python會採用E記法。例子:

Python學習筆記 - 字串,數字

E記法傳送門:科學記數法

在Python中 0.1 + 0.2 也是不等於 0.3 的,例子:

Python學習筆記 - 字串,數字

  • 自增和自減

    自增的操作符是 +=,自減的操作符是-=,例子:

    number = 10
    number += 1
    print(number) # 11
    number -= 1
    print(number) # 10
    複製程式碼

3. 型別轉換

  • float(),從一個字串或整數中建立一個新的浮點數
  • int(),從字串或浮點數中建立一個新的整數
  • str(),從一個數(可以是任何型別)中建立一個新的字串

例子:

Python學習筆記 - 字串,數字

  • type(),type方法可以檢測一個值的型別,例子:

Python學習筆記 - 字串,數字

4. Python之禪

在python的環境中可以用import this這句程式碼獲取“Python之禪”。例子:

Python學習筆記 - 字串,數字

相關文章