Try   HackMD

Python String(字串)操作

LHB阿好伯, 2020/03/13

tags: Python

字串建立

不管是R或Python中單引號或雙引號下的任何資料都是字串

資料型態-type() & class()

複習一下
而在Python確認資料格式的函數是使用 type()
而在R中則使用 class()

# R_Code T1 = 'AHB' print(class(T1)) T2 = "Hello, World!" print(class(T2))

[1] "character"
[1] "character"

# Python_Code T1 = 'AHB' print(type(T1)) T2 = 'Hello, World!' print(type(T2))

<class 'str'>
<class 'str'>

多行字串

Python比較特別可以用三重單引號(''')或雙引號(""")進行多行字串

# Python_Code multiline_string = '''I am a teacher and enjoy teaching. I didn't find anything as rewarding as empowering people. That is why I created 30 days of python.''' print(multiline_string)

I am a teacher and enjoy teaching.
I didn't find anything as rewarding as empowering people.
That is why I created 30 days of python.

在Rstudio中則是接受Enter換行
在輸出時則會顯示 \n 跳脫字元

T3 = "I am a teacher and enjoy teaching. I didn't find anything as rewarding as empowering people. That is why I created 30 days of python." print(T3)

[1] "I am a teacher and enjoy teaching. \nI didn't find anything as rewarding as empowering people. \nThat is why I created 30 days of python."

字串資料

字串合併

在python 中字串的連接可以直接使用加號合併 +
而在R語言中則可以使用 paste() or paste0()
這兩個差別在於字串合併間是否有空格

"1" + "2" + "3"

'123'

#R_Code paste("1", "2", "3") paste0("1", "2", "3")

"1 2 3"
"123"

跳脫字元(Escape Character)與ASCII

在字串中有一些特殊字元例如單引號、雙引號等特殊字元
需在前面加上一個反斜線 \ 才可以正常使用

跳脫字元 ASCII值 意義
\' 27 單引號
\" 22 雙引號
\\ 5C 反斜線
\a 07 control character BEL (a for alert)
\b 08 BackSpace 鍵
\f 0C 換頁
\n 0A 換行
\o 8 進位
\r 0D 游標移至最左側
\x 16 進位
\t 09 Tab鍵 (8 spaces)
\v 0B 垂直定位
#Python_Code print('a\nb') #換行 print("a\tb") #Tab (8 spaces) print("a\\b") #\\ Back slash print("a\'b") #\' Single quote (') print("a\"b") # \" Double quote (")

#換行
a
b
#Tab (8 spaces)
a b
#\ Back slash
a\b
#Single quote (')
a'b
#Double quote (")
a"b

String formating字串格式化

在python中,有許多格式化字符串的方法
把字串中的變數替換成變數值
以下為最常見的方式

  1. 舊式字串格式化
  2. 新式字串格式化
  3. 字串插值

舊式字串格式化

Python 3.6 版本之後推薦使用的新式字串格式化
舊式版本使用 % 運算子來進行字串格式化

sign funtion
%c 格式化字符及其ASCII碼
%s 格式化字符串
%d 格式化整數
%u 格式化無符號整型
%o 格式化無符號八進制數
%x 格式化無符號十六進制數
%X 格式化無符號十六進制數(大寫)
%f 格式化浮點數字,可指定小數點後的精度
%e 用科學計數法格式化浮點數
%E 作用同%e,用科學計數法格式化浮點數
%g %f和%e的簡寫
%G %f 和%E 的簡寫
%p 用十六進制數格式化變量的地址
# Strings and numbers radius = 10 pi = 3.14 area = pi * radius ** 2 formated_string = 'The area of circle with a radius %d is %.2f.' %(radius, area) # 2 refers the 2 significant digits after the point print(formated_string)

The area of circle with a radius 10 is 314.00.

若是仔細觀看範例
可以發現在格式化的使用可以說是非常麻煩
需要先定義格式化類型及位置
之後再定義格式化的內容
所以後面就衍生出新的格式化方式format()

新式字串格式化format()

其功能和舊式格式化相差無幾
但主要是捨去 % 讓字串格式化使用上可讀性提升許多

radius = 10 pi = 3.14 area = pi * radius ** 2 formated_string = 'The area of a cricle with a radius {} is {:.2f}.'.format(radius, area) # 2 digits after decimal print(formated_string)

Formatted String Literal字串插值

Python 3.6 新增了格式字串字面值Formatted String Literal此一作法可以把 Python 運算式嵌入在字串常數中
字符串以 f 開頭,我們可以將數據插入它們的相應位置

a = 4 b = 3 print(f'{a} + {b} = {a +b}') print(f'{a} - {b} = {a - b}') print(f'{a} * {b} = {a * b}') print(f'{a} / {b} = {a / b:.2f}') print(f'{a} % {b} = {a % b}') print(f'{a} // {b} = {a // b}') print(f'{a} ** {b} = {a ** b}')

4 + 3 = 7
4 - 3 = 1
4 * 3 = 12
4 / 3 = 1.33
4 % 3 = 1
4 // 3 = 1
4 ** 3 = 64

Python字符串作為字符序列

Python字符串是字符序列,並與其他Python排序的對象序列(列表和元組)共享其基本訪問方法

language = 'Python' a,b,c,d,e,f = language # unpacking sequence characters into variables print(a) # P print(b) # y print(c) # t print(d) # h print(e) # o print(f) # n

通過索引訪問字符串中的字符

在Python中索引計數從 開始
因此,字符串的第一個字母為0索引
而字符串的最後一個字母為字符串的長度-1。

language = 'Python' print(language[0]) #P print(language[1]) #y print(language[2]) #t

如果我們想從右端開始,我們可以使用負索引
-1 是最後一個索引

print(language[-1]) #n print(language[-2]) #o print(language[-3]) #h

反轉字符串

greeting = 'Hello, World!' print(greeting[::-1]) # !dlroW ,olleH

跳過片段

language = 'Python' pto = language[0,6:2] # print(pto) # Pto

常用字串函數

函數 說明 範例
capitalize() 將字符串的第一個字符轉換為大寫字母
count() 返回出現在字符串中的子字符串count(substring, start=.., end=..)
endswith() 檢查字符串是否以指定的結尾結尾 substring.endswith('text')
expandtabs() 用空格替換製表符,默認製表符大小為8。它採用製表符大小參數
find() 返回第一次出現的子字符串的最低索引,如果找不到則返回-1 substring.find('text')
rfind() 返回第一次出現的子字符串的最高索引,如果找不到則返回-1 substring.rfind('text')
index() 返回子字符串的最低索引,其他參數指示開始和結束索引 substring.index('text', start=…, end=…)
rindex() 返回子字符串的最高索引,其他參數指示開始和結束索引(默認為0,字符串長度為1) substring.rindex('text', start=…, end=…)
isalnum() 檢查字母數字字串 substring.isalnum()
isalpha() 檢查所有字串串元素是否都是字母字符(az和AZ) substring.isalpha()
isdecimal() 檢查字符串中的所有字串是否均為十進制(0-9) substring.isdecimal()
isdigit() 檢查字符串中的所有字串是否都是數字(0-9和其他一些unicode字符用於數字) substring.isdigit()
isnumeric() 檢查字符串中的所有字串是否都是數字或與數字相關(就像isdigit()一樣,只接受更多符號,例如½)
isidentifier() 檢查有效的標識符-表示它檢查字串是否為有效的變量名
islower() 檢查字串中的所有字母字符是否都小寫
isupper() 檢查字串中的所有字母字符是否都大寫
join() 串聯字符串
strip() 刪除字串中所有給定的字串
replace() 用給定的字串替換子字符串
split() 使用給定的字串作為分隔符來拆分字串
title() 返回標題大寫的字符串
swapcase() 將所有大寫字符轉換為小寫,並將所有小寫字符轉換為大寫
startswith() 檢查字符串是否以指定的字符串開頭 substring.startswith('text')

全文分享至

https://www.facebook.com/LHB0222/

有疑問想討論的都歡迎於下方留言

喜歡的幫我分享給所有的朋友 \o/

有所錯誤歡迎指教