Python String split() Metode
Voorbeeld
Verdeel 'n string in 'n lys waar elke woord 'n lysitem is:
txt = "welcome to the jungle"
x = txt.split()
print(x)
Definisie en gebruik
Die split()
metode verdeel 'n string in 'n lys.
Jy kan die skeier spesifiseer, verstek skeier is enige witspasie.
Let wel: Wanneer maxsplit gespesifiseer is, sal die lys die gespesifiseerde aantal elemente plus een bevat .
Sintaksis
string.split(separator, maxsplit)
Parameterwaardes
Parameter | Description |
---|---|
separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences" |
Meer voorbeelde
Voorbeeld
Verdeel die string, met behulp van kommas, gevolg deur 'n spasie, as 'n skeiding:
txt = "hello, my name is Peter, I am 26 years old"
x = txt.split(", ")
print(x)
Voorbeeld
Gebruik 'n hash-karakter as 'n skeiding:
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
Voorbeeld
Verdeel die string in 'n lys met maksimum 2 items:
txt = "apple#banana#cherry#orange"
# setting the maxsplit parameter
to 1, will return a list with 2 elements!
x = txt.split("#", 1)
print(x)