相比较C++而言,Python 对于String的操作更为的容易,比如Split的操作
txt = "welcome to the jungle"
x = txt.split()
print(x)
// ['welcome', 'to', 'the', 'jungle']
语法规则
string.split(separator, maxsplit)
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”
txt = "hello, my name is Peter, I am 26 years old"
x = txt.split(", ")
print(x)
//['hello', 'my name is Peter', 'I am 26 years old']
txt = "apple#banana#cherry#orange"
x = txt.split("#")
print(x)
//['apple', 'banana', 'cherry', 'orange']
txt = "apple#banana#cherry#orange"
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.split("#", 1)
print(x)
//['apple', 'banana#cherry#orange']