Python切片字符串

Python 字串支援切片以建立子字串。請注意 Python 字串是不可變的,切片會從原始字串中建立新的子字串,原始字串保持不變。

Python 切片字串

Python 切片字串的語法如下:

str_object[start_pos:end_pos:step]

切片從起始位置索引(包括)開始,到結束位置索引(不包括)結束。步驟參數用於指定從起始到結束索引的步驟。Python 字串切片始終遵循此規則:s[:i] + s[i:] == s,對於任何索引‘i’。所有這些參數都是可選的 – 起始位置的默認值為 0,結束位置的默認值為字串長度,步驟的默認值為 1。讓我們看一些使用字串切片函數來建立子字串的簡單示例。

s = 'HelloWorld'

print(s[:])

print(s[::])

輸出:

HelloWorld
HelloWorld

請注意,由於未提供任何切片參數,所以子字串等於原始字串。讓我們看一些更多切割字串的示例。

s = 'HelloWorld'
first_five_chars = s[:5]
print(first_five_chars)

third_to_fifth_chars = s[2:5]
print(third_to_fifth_chars)

輸出:

Hello
llo

請注意索引值從 0 開始,所以起始位置 2 指的是字串中的第三個字符。

使用切片反轉字串

我們可以通過將步驟值設置為 -1 來使用切片來反轉字串。

s = 'HelloWorld'
reverse_str = s[::-1]
print(reverse_str)

dlroWolleH 讓我們來看一些使用步驟和負索引值的其他範例。

s1 = s[2:8:2]
print(s1)

輸出:loo 在這裡,子字串包含索引2、4和6的字符。

s1 = s[8:1:-1]
print(s1)

輸出:lroWoll 這裡的索引值是從尾部到開始取的。子字串是由尾部的索引1到7組成的。

s1 = s[8:1:-2]
print(s1)

輸出:lool Python的切片也支持負索引,此時,起始位置不包括在子字串內,而結束位置則包括在內。

s1 = s[-4:-2]
print(s1)

輸出:or Python字符串切片能夠優雅地處理超出範圍的索引。

>>>s = 'Python'
>>>s[100:]
''
>>>s[2:50]
'thon'

這就是Python字符串切片函數創建子字串的全部內容。

您可以在我們的GitHub存儲庫中查看完整的Python腳本和更多Python示例。

Source:
https://www.digitalocean.com/community/tutorials/python-slice-string