002---Python基本資料型別--字串
字串的定義與建立
定義:字串是一個有序的字元集合,用來儲存和表示文字資訊。用雙引和單引表示。是一種不可變型別。
In [9]:
s = 'Hello Python' print(s)
Hello Python
In [1]:
# 索引和切片 s = 'Python' print(s[1])# y print(s[-1])# n print(s[1:4]) # yth顧頭不顧尾
y n yth
In [2]:
# capitalize()首字母大寫 s = 'hello python' print(s.capitalize())# Hello python
Hello python
In [3]:
# upper()lower()全大寫和全小寫 s1 = 'hello python' s2 = 'HELLO PYTHON' print(s1.upper())# Hello python print(s2.lower())# hello python
HELLO PYTHON hello python
In [4]:
# title()每個隔開(特殊字元和數字)的單詞的首字母大寫 s = 'life is short you need python' print(s.title())# Life Is Short You Need Python
Life Is Short You Need Python
In [11]:
# center()兩邊按指定字元填充居中 s = 'python' print(s.center(20,'-'))# -------python-------
-------python-------
In [10]:
#len()長度字元數 s = 'i love you jiang zi ya' print(len(s))# 22 s1 = '我喜歡你' print(len(s1)) # 4
In [16]:
# startswith()判斷是否以什麼什麼開頭支援指定起始和終止 s = 'jiang ziya' print(s.startswith('jiang'))# True print(s.startswith('ziya'))# False print(s.startswith('jiang',0,5)) # True print(s.startswith('jiang',0,4)) # False
True False True False
In [19]:
# find()查詢每個字元的索引沒找到返回-1支援指定起始和終止 s = 'jiang zi ya' print(s.find('z')) print(s.find('zi')) print(s.find('Jiang'))
6 6 -1
In [20]:
# index()查詢每個字元的索引沒找到報錯 print(s.index('z')) print(s.index('zi')) # print(s.index('Jiang'))
--------------------------------------------------------------------------- ValueErrorTraceback (most recent call last) <ipython-input-20-ff6187789150> in <module> 2 print(s.index('z')) 3 print(s.index('zi')) ----> 4print(s.index('Jiang')) ValueError: substring not found
In [36]:
# strip()去除兩邊的指定字串預設刪空格rstrip() 左邊lstrip()右邊 s = 'python' print(s.strip()) print(s.strip('')) print(s.strip(' ')) print(''.center(20,'-')) s1 = '*%jiang*%wei*%%%%' print(s1.strip('*%'))
python python python -------------------- jiang*%wei
In [46]:
# count() 計算某個字元的個數 支援指定起始和終止位置 s = 'Python python' print(s.count('t')) print(s.count('jiang'))
In [58]:
# split()按照指定字元切割預設按照空格切割返回列表 s = ' i love you ' print(s.split()) print(s.split(' ')) s1 = '--he--he--he--' print(s1.split('--'))
['i', 'love', 'you'] ['', 'i', 'love', 'you', ''] [' i love you '] ['', 'he', 'he', 'he', '']
In [61]:
# replace() 替換 可以指定替換數 s = 'who are you who are you who are you' print(s.replace('you','she')) print(s.replace('you','she',2))
who are she who are she who are she who are she who are she who are you
In [69]:
# is系列 name = 'jiangziya1' print(name.isalpha())# 判斷字串是否由字母組成 print(name.isalnum())# 判斷字串是否由數字和字母組成 print(name.isdigit())# 判斷字串是否右數字組成
False True False