# @time:2020/12/12 14:33
# @author:李 祥
# @file:string.py
# @software:pycharm
# 1.字串string
# python中沒有字元型別,乙個字元也是字串型別
# utf-8編碼 所有字串都是unicode字串
# 單引號 雙引號 三引號
word =
'string'
sentence =
"this is sentence"
paragraph =
""" more
this is paragraph
"""# 2.轉義字元
my_str =
"i'm a student"
my_str1 =
'i\'m a student'
my_str2 = r'i\'m a student'
# 轉義不生效
# # 3.字串切片(字串的擷取)
str1 =
"student"
#正索引-----0123456
#負索引----- -7.....-1
(len
(str1)
)#內建函式len() 獲取長度
(str1[2:
6])#擷取
(str1[2:
6:2]
)#左閉,右開,間隔步長
(str1[::
-1])
#倒著列印
# 4.字串的拼接
str1 =
"student"
str1 +=
"study"
(str1)
('*'*30
)str2 =
"tooooooooooooooooooo"\
"long"\
"write"
(str2)
# 5.string 常用函式
# 5.1 字母轉換
# capitalize 首字母大寫
str1 =
"student"
res = str1.capitalize(
(res)
# title 每個單詞的首字母大寫
str1 =
"student and teacher "
res = str1.title(
(res)
res = str1.istitle(
)#判斷是否每個單詞首字母大寫
(res)
# upper 全大寫
# lower 全小寫
# swapcase 大小寫互換
# 5.2 統計和查詢
# count 統計字串中某個元素的數量
str1 =
"students"
res = str1.count(
"s")
#區分大小寫,可為字串
(res)
# find 查詢某個字元第一次出現的位置
# find("字串",開始位置,結束位置) 結束位置取不到,取到之前的乙個值。取不到為-1
# index 與 find 功能相同。find找不到返回-1,而index取不到會報錯。
# 5.3判斷開頭、結尾
# startswith 判斷是否以某個字元或字串為開頭
# startswith('字串',開始位置,結束位置) 返回為true或false
# endswith 判斷是否以某個字元或字串為結尾
# endswith('字串',開始位置,結束位置) 返回為true或false
# 5.4分割與拼接
# split 按某字元將字串分割成 列表(預設從左到右按空格分隔)
# split("字串", 切割個數)
str1 =
"我_是_憨_憨"
res = str1.split(
"_",1)
(res)
# rsplit 從右往左排列 注意前面有r
# join 按某字元將列表拼接成字串(容器型別都可)
list1 =
["st"
,"ud"
,"ent"
]res =
"-".join(list1)
(res)
# 5.5去掉與替換
# replace 替換字串(第三個引數選擇替換的次數)
str1 =
"student"
res = str1.replace(
"stu"
,"aaa"
(res)
res = str1.replace(
"t",
"a",1)
(res)
# strip 預設去掉首位兩邊的空白符
str1 =
"\r student \t \n"
(str1)
res = str1.strip(
(res)
# lstrip() 只去掉左側空白符
# rstrip() 只去掉右側空白符
# 5.6判斷型別
# isspace() 字串中只包含空白 返回true 否則返回false
res =
" "
(res.isspace())
# isalpha() 字串是否為純字母
res =
"abc1"
(res.isalpha())
res =
"abc"
(res.isalpha())
res =
"#a"
(res.isalpha())
# isalnum() 字串至少乙個字元,所有字元都有字母或者數字
res =
"a"print
(res.isalnum())
res =
"1.1"
(res.isalnum())
res =
"1"print
(res.isalnum())
# isdecimal 檢測字串是否以數字組成,必須是純數字
# isdigit() 字串只包含數字則返回true,否則返回false
# isnumeric() 字串只包含數字字元,返回true,否則返回false
# 差別在 漢字數字 羅馬數字 byte數字
# 5.7長度、填充
# len()計算長度
# center 填充字串,原字元居中(預設空格填充)
str1 =
"student"
res = str1.center(10,
"*")
(res)
# 5.8 編碼和解碼
# max 返回字串編碼最大的字母
# min 返回字串編碼最小的字母
# ord 內建函式,返回漢字或字母的unicode編碼
# chr 內建函式,給定unicode編碼 返回字串
str1 =
"學生"
str_utf8 = str1.encode(
"utf-8"
)str_gbk = str1.encode(
"gbk"
(f"urf-8編碼:"
(f"gbk編碼:"
(f"urf-8解碼:"
(f"gbk解碼:"
)
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...