Python string 方法
- 字元串指派
- 多行字元串指派
- 字元串中單個字元引用
- len()---擷取字元串長度
- 判斷字元是否在字元串中
- 簡單字元串拼接
- 字元串中插入字元
- index()
- 示例一
字元串指派
str1 = "I am best"
多行字元串指派
str1 = """Today, the weather is good.
And my mood is also good.
I like summer day!
"""
字元串中單個字元引用
str1 = "I am best"
print(str1[0])
print([str1[1]])
print([str1[2]])
print([str1[3]])
print([str1[4]])
print([str1[5]])
print([str1[6]])
print([str1[7]])
print([str1[8]])
print([str1[-1]])
"""
result:
I
a
m
b
e
s
t
t
"""
字元串本身是一個可疊代對象,是以可以像數組元素一樣,使用下标來對字元串中的單個字元進行引用。注意:
str1[-1]
表示引用的是字元串中的倒數第一個元素。
這裡我們來看一個特殊情況。
str1 = "I"
print(str1)
print(str1[0])
print(str1[-1])
"""
result:
I
I
I
"""
如果我們的字元串僅有一個字元,我們可以将其視作一個字元,那麼此時
str1
,
str1[0]
與
str1[-1]
所獲得的值會是一樣的。
len()—擷取字元串長度
str1 = "abc"
print(len(str1))
"""
result:
3
"""
判斷字元是否在字元串中
str1 = "abc"
if 'a' in str1:
print("字元a在字元串abc中")
if 'd' not in str1:
print("字元d不在字元串abc中")
"""
result:
字元a在字元串abc中
字元d不在字元串abc中
"""
簡單字元串拼接
str1 = "I"
str2 = " "
str3 = "am"
str4 = "the"
str5 = "best"
result = str1 + str2 + str3 + str2 + str4 + str2 + str5
print(result)
"""
result:
I am the best
"""
字元串中插入字元
可以檢視這一篇Python 在字元串中某個單個字元兩側添加*(超連結點選跳轉)。
index()
調用方法:
string.index(value, start, end)
這裡的
value
為必要參數,
start
與
end
均為可選參數,
start
預設值為
0
,
end
的預設值為
len(string)
,即目前字元串的長度。
用法說明:
從左向右依次周遊整個目标字元串,找出目标字元在目标字元串中第一次出現的索引值。生成一個錯誤,如果目标字元串中查找不到目标字元。
index()
方法與
find()
方法幾乎一緻,隻是
index()
方法查找不到時會報錯,而
find()
方法查找不到時會傳回
-1
。
示例一
str1 = "abcba"
value = 'a'
result = str1.index(value)
print(result)
"""
result:
0
"""
可以看到,結果為
0
,我們輸出的是從左向右查找到的第一個字元
a
的索引值。那麼問題來了,我們如果想要找到第二個
a
的索引值該怎麼辦呢?可以使用如下代碼。
str1 = "abcba"
value = 'a'
index = str1.index(value)
result = str1.index(value, index+1)
print(result)
"""
result:
4
"""
我們通過指定起始搜尋的索引位置來規避第一個
a
,進而得到了第二個字元
a
所對應的索引值。可以進一步推廣,如果我們想要查找字元串中第
n
個
a
字元所對應的索引值呢?這裡以
n=10
舉例。
str1 = "abababababcbaaaaaa"
value = 'a'
num = 10 # 第十個a對應的索引值
index = 0
for i in range(num):
index = str1.index(value, index)
index = str1.index(value, index + 1)
print(index)
"""
result:
17
"""