Python-split()函数实例用法讲解

Python itxz 3年前 (2020-12-21) 369次浏览 已收录 0个评论

在Python中,split() 方法可以实现将一个字符串按照指定的分隔符切分成多个子串,这些子串会被保存到列表中(不包含分隔符),作为方法的返回值反馈回来。

<a href="http://www.itxz.com/?tag=split" title="查看更多关于split的文章" target="_blank">split</a>(sep=None, max<a href="http://www.itxz.com/?tag=split" title="查看更多关于split的文章" target="_blank">split</a>=-1)

实例

// 例子
String = 'Hello world! Nice to meet you'
String.<a href="http://www.itxz.com/?tag=split" title="查看更多关于split的文章" target="_blank">split</a>()
['Hello', 'world!', 'Nice', 'to', 'meet', 'you']
String.split(' ', 3)
['Hello', 'world!', 'Nice', 'to meet you']
String1, String2 = String.split(' ', 1) 
// 也可以将字符串分割后返回给对应的n个目标,但是要注意字符串开头是否存在分隔符,若存在会分割出一个空字符串
String1 = 'Hello'
String2 = 'world! Nice to meet you'
String.split('!')
// 选择其他分隔符
['Hello world', ' Nice to meet you']
def split(self, *args, **kwargs): # real signature unknown
   """
   Return a list of the words in the string, using sep as the delimiter string.
    sep
     The delimiter according which to split the string.
     None (the default value) means split according to any whitespace,
     and discard empty strings from the result.
    maxsplit
     Maximum number of splits to do.
     -1 (the default value) means no limit.
   """
   pass

上图为Pycharm文档

def my_split(string, sep, maxsplit):
  ret = []
  len_sep = len(sep)
  if maxsplit == -1:
    maxsplit = len(string) + 2
  for _ in range(maxsplit):
    index = string.find(sep)
    if index == -1:
      ret.append(string)
      return ret
    else:
      ret.append(string[:index])
      string = string[index + len_sep:]
  ret.append(string)
  return ret
if __name__ == "__main__":
  print(my_split("abcded", "cd", -1))
  print(my_split('Hello World! Nice to meet you', ' ', 3))

IT学者 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python-split()函数实例用法讲解
喜欢 (0)

您必须 登录 才能发表评论!