Python 字串基礎

2021-10-01 08:57:29 字數 2359 閱讀 6125

字串是 python 中最常用的資料型別。我們可以使用引號( 』 或 " )來建立字串。

a= 'hello world!'

b = "runoob"

在需要在字元中使用特殊字元時,python用反斜槓()轉義字元。如下:

(在行尾時) 續行符

\ 反斜槓符號

』 單引號

" 雙引號

\a 響鈴

\b 退格(backspace)

\n 換行

\v 縱向製表符

\t 橫向製表符

\r 回車

\f 換頁

1.判斷字串是否以指定內容開頭

startswith :從前向後一樣的

2.判斷字串是否以指定內容結尾 —> 檔案字尾名的判斷

endswith: 從後向前是一樣的

判斷字串的內容是否是純數值的

isdigit

判斷字串的內容是否是純字母的

isalpha

判斷字串的內容是否是由字母或者數字組成的

isalnum

判斷字串的字母是否是大寫字母的

isupper

判斷字串的字母是否是小寫字母的

islower

判斷字串的內容是否是空白的

isspace

1.將字串中的字母轉化為大寫

upper

new_s = "hello".upper()

print(new_s)

2.將字串中的字母轉化為小寫

lower

new_s = "hello".lower()

print(new_s)

3.將字串中的大寫字母轉化為小寫, 將小寫字母轉化為大寫

swapcase

new_s = 「hello」.swapcase()

print(new_s)

4.將字串的首字母轉化為大寫

capitalize

new_s = 「good good study」.capitalize()

print(new_s)

5.將字串中每個單詞的首字母轉化為大寫

單詞: 用空格或者是標點符號分割開來的 字母 就稱作單詞

title

new_s = 「good good study」.title()

print(new_s)

『』』s = 「good good study」

#替換哪個子串 替換成什麼

replace_s = s.replace(「oo」, 「o」)

print(replace_s)

replace_s = s.replace(「oo」, 「o」, 1)

print(replace_s)

split

--- 根據指定的切割符 將字串切成n個片段, 結果會生成乙個列表 儲存這n個片段

if sep is not specified or is none, any

whitespace string is a separator and empty strings are

removed from the result.

如果沒有設定切割符 會以任意空白字串為切割符

可能結果中會有空字串的存在 這個空字串會被在結果中移除

# 指定要移除的字串

s = 「abc***abc

strip_s = s.strip("*")

print(strip_s)

只移除左邊

l_strip_s = s.lstrip("*")

print(l_strip_s)

只移除右邊

r_strip_s = s.rstrip("*")

print(r_strip_s)

指定乙個字串寬度 讓字串左對齊

ljust

指定乙個字串寬度 讓字串右對齊

rjust

指定乙個字串寬度 讓字串居中對齊

center

"拼接符".join(序列)

----> 注意: 序列中的元素必須是字串型別的

『』』

s = 「abc」

b = 12

#typeerror: must be str, not int

str_list = [「hello」, 「nice」, 「bye」 ,「good」, 「bye」]

join_str = " ".join(str_list)

print(join_str)

python基礎 字串

轉義符 n換行 print 我是 nzzz 我是 zzz t製表符 print 我是 tzzz 我是 zzz 雙引號 print 我是 zzz 我是 zzz 單引號 print 我是 zzz 我是 zzz 續航符 name s z print name sz原始字串 原始字串 r abc r abc...

Python基礎字串

str1 hello python str1 str1.capitalize 把開頭轉換成大寫 print str1 str1 str1.center 8,居中並填充 print str1 str1 str1.find j 0,len str1 尋找元素所在的位置,沒在返回 1 print str1...

Python基礎 字串

判斷全部否是字母 str helloween if str.isalpha print 字母 判斷全部否是數字 str 1234 if str.isdecimal print 數字 判斷都是大寫 str abc if str.isupper print 大寫 判斷都是小寫 str abc if st...