split()函数如何在Python中使用

发布时间:2020-12-18 14:09:35 作者:Leah
来源:亿速云 阅读:180

split()函数如何在Python中使用?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

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

split函数用法

split(sep=None, maxsplit=-1)

参数

sep – 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。

maxsplit – 分割次数。默认为 -1, 即分隔所有。

实例:

// 例子
String = 'Hello world! Nice to meet you'
String.split()
['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']

split函数实现

 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))

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. Web开发是用PHP还是Python更好
  2. 好程序员Python教程分享python之变量

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python split()

上一篇:BeautifulSoup库怎么在python中安装与使用

下一篇:模拟信号和数字信号有什么区别

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》