共計 367 個字符,預(yù)計需要花費 1 分鐘才能閱讀完成。
要訪問字符串中的單個字符,可以使用索引操作符 [] 來獲取特定位置的字符。Python 中的字符串是一個字符序列,每個字符都有一個唯一的索引值,從 0 開始計數(shù)。
例如,要訪問字符串“Hello”中的第一個字符“H”,可以使用索引值 0 來獲取:
string = "Hello"
first_char = string[0]
print(first_char) # Output: H
同樣,可以使用負數(shù)索引值來從字符串末尾開始訪問字符。例如,要訪問字符串“World”中的最后一個字符“d”,可以使用索引值 -1:
string = "World"
last_char = string[-1]
print(last_char) # Output: d
通過索引值訪問字符串中的單個字符是一種方便且常見的操作,使得我們能夠輕松地獲取和操作字符串中的特定字符。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完