iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 10
0
自我挑戰組

從python入門到物聯網系列 第 10

Day10 - 字串處理

字串運用 - 單引號、雙引號括起來的都是字串。
字串的常見用法:

字串切割 - split()

當我們輸入的文字檔或者接收到的資料,可以利用split()切割字串,
轉換成 list 方便後續分析處理。

str.split(str=''). #' ' 填入要分割的符號

範例:

str1 = 'bear, cat, dog, elephant'
arr = str1.split(', ')
print(arr)

結果:

['bear', 'cat', 'dog', 'elephant']
  • 字串印出格式
    • \n => 換行
    • \t => 空格(四格)
  1. \n => 換行
print('hello world\npython')

結果:

hello world
python
  1. \t => 空格(四格)
print('hello world\tpython')

結果:

hello world    python
  • 取得特定範圍的字串
    string 和 list 一樣都可以取特定部分的內容
str1 = 'hello world'

print (str1)      # 輸出完整的str
print (str1[0])   # 輸出str1索引值0的位置 => 第一個字元
print(str1[-3])   # 輸出str1索引值-3的位置 => 倒數第三個字元
print (str1[1:8]) # 輸出第二到第八個字元
print (str1[1:])  # 輸出第二到最後一個字元
print (str1[:7])  # 輸出第一到第七個字元

結果:

hello world
h
r
ello wo
ello world
hello w
  • 大小寫轉換
str1 = 'hello world!'

print(str1.upper())      #全部字元轉成大寫
print(str1.lower())      #全部字元轉成小寫
print(str1.swapcase())   #將大小寫顛倒

print(str1.title())      #每個單字首字大寫
print(str1.capitalize()) #第一個字母大寫
  • len() => 計算字串長度
str1 = 'hello world!'
str2 = 'python!'
print(len(str1),len(str2))
  • replace()
str.replace(old, new[, max])

參數
old -> 要更換的字串。
new -> 新的字串。
max -> 最多換掉幾次。

str1 = "Today is great for learning python! That is good! This is example"
print(str1.replace("is", "was"))
print(str1.replace("is", "was", 2))

結果

Today was great for learning python! That was good! Thwas was example
Today was great for learning python! That was good! This is example
  • 字串比對
import operator
str1 = 'hello world!'
str2 = 'hello'
print(operator.eq(str1,str2))

結果為

False
  • find()
str.find(str, beg=0 end=len(string))

參數
str -> 要找的字串。
beg -> 開始找的位置。
end -> 結束的位置。

回傳
如果有找到就回傳位置,沒有找到則回傳-1

str1 = 'hello world!'
str2 = 'hello'
print(str1.find(str2))
  • join()
str.join(sequence)

範例:

str1 = ' & '
tup = ('a', 'b', 'c')
print(str1.join(tup))

參考資料

http://tw.gitbook.net/python/python_strings.html


上一篇
Day09 - While迴圈
下一篇
Day11 - Python 如何處理 JSON
系列文
從python入門到物聯網30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
fuhu
iT邦新手 5 級 ‧ 2022-03-12 15:43:24

\t 應該是[Tab], 應該就像您在Day6中提到的, Tab與四個空格不同, 只不過在這裡, Python終端解釋Tab剛好是4個空格

我要留言

立即登入留言