• 技术文章 >Python技术 >Python基础教程

    python怎么把一个字符串切开

    FXLFXL2020-08-27 10:02:09原创4497

    split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串,并返回分割后的字符串列表。

    (推荐教程:Python入门教程

    语法:

    1

    str.split(str="", num=string.count(str))

    参数:

    代码示例:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    #定义一个字符串str1

    >>> str1 = "3w.gorly.test.com.cn"

      

    #使用默认分隔符分割字符串str1

    >>> print str1.split()

    ['3w.gorly.test.com.cn']

      

    #指定分隔符为'.',进行分割字符串str1

    >>> print str1.split('.')

    ['3w', 'gorly', 'test', 'com', 'cn']

      

    #指定分隔符为'.',并且指定切割次数为0次

    >>> print str1.split('.',0)

    ['3w.gorly.test.com.cn']

      

    #指定分隔符为'.',并且指定切割次数为1次

    >>> print str1.split('.',1)

    ['3w', 'gorly.test.com.cn']

      

    #指定分隔符为'.',并且指定切割次数为2次

    >>> print str1.split('.',2)

    ['3w', 'gorly', 'test.com.cn']

      

    #这种分割等价于不指定分割次数str1.split('.')情况

    >>> print str1.split('.',-1)

    ['3w', 'gorly', 'test', 'com', 'cn']

      

    #指定分隔符为'.',并取序列下标为0的项

    >>> print str1.split('.')[0]

    3w

      

    #指定分隔符为'.',并取序列下标为4的项

    >>> print str1.split('.')[4]

    cn

    专题推荐:python 字符串
    上一篇:python中怎么安装jieba库 下一篇:python如何打印直角三角形

    相关文章推荐

    • python中字符串如何反转• python怎么判断字符串中包含特殊符号• python怎样遍历字符串

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网