一、split()函數與rsplit()函數的使用
在日常的字符串處理中,又怎能少得了Python中的split()函數呢?這個函數能夠將字符串按照指定的分隔符(默認為空格)分成多個子字符串,並返回所有子字符串組成的列表。
str = "hello world python" result = str.split() print(result) # ['hello', 'world', 'python'] str = "hello-world-python" result = str.split('-') print(result) # ['hello', 'world', 'python']
如果我們想要從右往左分割字符串,並只分割一次,那麼可以使用rsplit()函數。其接受兩個參數,第一個參數為分隔符,第二個參數為分割次數。
str = "hello world python" result = str.rsplit() print(result) # ['hello', 'world', 'python'] str = "hello-world-python" result = str.rsplit('-', 1) print(result) # ['hello-world', 'python']
二、String方法中使用split()函數與rsplit()函數
除了直接調用split()和rsplit()函數外,split()函數和rsplit()函數也可以在String方法中使用。
str = "hello world python" result = str.split() print(result) # ['hello', 'world', 'python'] result = "hello world python".split() print(result) # ['hello', 'world', 'python'] str = "hello-world-python" result = str.split('-') print(result) # ['hello', 'world', 'python'] result = "hello-world-python".split('-') print(result) # ['hello', 'world', 'python']
同樣的,rsplit()函數也可以在String方法中使用。
str = "hello world python" result = str.rsplit() print(result) # ['hello', 'world', 'python'] result = "hello world python".rsplit() print(result) # ['hello', 'world', 'python'] str = "hello-world-python" result = str.rsplit('-', 1) print(result) # ['hello-world', 'python'] result = "hello-world-python".rsplit('-', 1) print(result) # ['hello-world', 'python']
三、如何使用split()函數和rsplit()函數截止至指定字符並分割字符串
如果我們想按照指定的字符或者字符串截止並分割一個字符串,應該怎麼辦呢?split()函數和rsplit()函數同樣可以勝任。
str = "hello_world_python" result = str.split('_', 1) print(result) # ['hello', 'world_python'] result = str.rsplit('_', 1) print(result) # ['hello_world', 'python']
上面的代碼中,我們將原始字符串按照’_’進行分割,分割的次數為1,也就是只分割一次。可以看到,使用split()函數時,返回的列表中第一元素為第一個’_’前面的部分,第二個元素為第一個’_’後面的部分。使用rsplit()函數時,返回的列表中最後一個元素為最後一個’_’後面的部分,其他元素為最後一個’_’前面的部分。
完整示例代碼
# split()函數和rsplit()函數的使用 str = "hello world python" result = str.split() print(result) # ['hello', 'world', 'python'] str = "hello-world-python" result = str.split('-') print(result) # ['hello', 'world', 'python'] str = "hello world python" result = str.rsplit() print(result) # ['hello', 'world', 'python'] str = "hello-world-python" result = str.rsplit('-', 1) print(result) # ['hello-world', 'python'] # String方法中使用split()函數和rsplit()函數 result = "hello world python".split() print(result) # ['hello', 'world', 'python'] result = "hello-world-python".split('-') print(result) # ['hello', 'world', 'python'] result = "hello world python".rsplit() print(result) # ['hello', 'world', 'python'] result = "hello-world-python".rsplit('-', 1) print(result) # ['hello-world', 'python'] # 如何使用split()函數和rsplit()函數截止至指定字符並分割字符串 str = "hello_world_python" result = str.split('_', 1) print(result) # ['hello', 'world_python'] result = str.rsplit('_', 1) print(result) # ['hello_world', 'python']
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/308395.html