字串就是一串字符,是編程語言中表示文本的資料型別,
字串是 Python 中最常用的資料型別,
字串的宣告
在 Python 中可以使用一對雙引號"或者一對單引號'定義一個字串,
那么在開發時,是使用雙引號還是使用單引號呢?
首先呢,大多數編程語言都是用雙引號來定義字串,所以我們在開發時更傾向使用雙引號,這樣可以和其他編程語言相通,
雖然可以使用\"或者\'做字串的轉義,但是在實際開發中:
如果字串內部需要使用雙引號,那么可以使用單引號定義字串,
如果字串內部需要使用單引號,可以使用雙引號定義字串,
str1 = '我的外號是"大西瓜"'
print(str1)
# 我的外號是"大西瓜"
三引號宣告字串變數
還有一種特別的情況,就是需要宣告的字串中包含換行符、制表符、以及其他特殊字符的時候,我們可以使用三引號來進行賦值,
Python 中三引號宣告變數就是針對復雜的字串,
三引號的語法是一對連續的單引號或者雙引號(通常都是成對的用),
hi = '''hi
there'''
print(hi)
# hi
# there
三引號宣告字串可以自始至終保持一小塊字串的格式是所謂的所見即所得格式的,
一個典型的用例是,當你需要一塊HTML或者SQL時,這時用三引號標記非常方便,使用傳統的轉義字符體系將十分費神,
字串索引概念
之前學習串列元祖都有索引的概念,我們同樣可以把字串看成是存盤多個字符的大柜子,在每個小格子中存盤一個又一個字符,
所以我們同樣可以使用索引獲取一個字串中指定位置的字符,索引計數也是從0開始的,

str1 = "hello python"
print(str1[6])
# p
我們也同樣可以使用 for 回圈通過迭代遍歷的方式讀取字串中每一個字符,
實體
string = "Hello Python"
for char in string:
print(c)
字串的常用操作
python 提供的字串操作方式特別多,但正是因為 python 提供的方法足夠多,才使得在開發時,能夠針對字串進行更加靈活的操作,應對更多的開發需求!
這里只介紹幾個常用的字串方法,剩余的在實際開發中用到的時候翻閱手冊即可,多用就記住了,
len 統計字串長度
hello_str = "hello hello"
print(len(hello_str))
# 11
count 統計某一個小(子)字串出現的次數
hello_str = "hello hello"
print(hello_str.count("llo"))
print(hello_str.count("abc"))
# 2
# 0 子串不存在時,程式不報錯,
isspace 判斷空白字符,
space_str = " \t\n\r"
print(space_str.isspace())
# True
判斷字串中是否只包含數字,
num_str = "1.1"
# 都不能判斷小數
print(num_str.isdecimal()) # False
print(num_str.isdigit()) # False
print(num_str.isnumeric()) # False
# unicode 字串
num_str = "\u00b2"
print(num_str.isdecimal()) # False
print(num_str.isdigit()) # True
print(num_str.isnumeric()) # True
# 中文數字
num_str = "一千零一"
print(num_str.isdecimal()) # False
print(num_str.isdigit()) # False
print(num_str.isnumeric()) # True
startswith 判斷是否以指定字串開始
hello_str = "hello world"
print(hello_str.startswith("Hello"))
# False
endswith 判斷是否以指定字串結束
hello_str = "hello world"
print(hello_str.endswith("world"))
# True
index 查找某一個子字串出現的位置
hello_str = "hello hello"
print(hello_str.index("llo"))
# 2
# 使用index方法傳遞的子字串不存在,程式會報錯
print(hello_str.index("abc"))
# ValueError: substring not found
find 查找某一個子字串出現的位置
hello_str = "hello world"
print(hello_str.find("llo"))
# 2
# find如果指定的字串不存在,會回傳-1
print(hello_str.find("abc"))
# -1
replace 替換字串
hello_str = "hello world"
print(hello_str.replace("world", "python"))
# hello python
print(hello_str)
# hello world
replace方法執行完成之后,會回傳一個新的字串,不會修改原有字串的內容,所以需要一個變數去接收,
strip 洗掉字串中多余的空格和特殊字符
str = " www.daydaylearn.cn \t\n\r"
print(str)
str2 = str.strip()
# 并不會改變字串本身,需要新的變數接收,
print(str2)
# www.daydaylearn.cn
#www.daydaylearn.cn
在 str.strip([chars]) 中,[chars] 用來指定要洗掉的字符,可以同時指定多個,如果不手動指定,則默認會洗掉空格以及制表符、回車符、換行符等特殊字符,
split 拆分字串
poem_str = "登鸛雀樓\t 王之渙 \t 白日依山盡 \t \n 黃河入海流 \t\t 欲窮千里目 \t\t\n更上一層樓"
poem_list = poem_str.split()
print(poem_list)
# ['登鸛雀樓', '王之渙', '白日依山盡', '黃河入海流', '欲窮千里目', '更上一層樓']
join 合并字串
poem_list = ['登鸛雀樓', '王之渙', '白日依山盡', '黃河入海流', '欲窮千里目', '更上一層樓']
result = " ".join(poem_list)
print(result)
# 登鸛雀樓 王之渙 白日依山盡 黃河入海流 欲窮千里目 更上一層樓

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/47282.html
標籤:Python
