2022年 11月 3日

Python –如何分割字符串

很少有示例向您展示如何在Python中将字符串拆分为列表。

1.按空格分割

默认情况下, split()将空格用作分隔符。

  1. alphabet = "a b c d e f g"
  2. data = alphabet.split() #split string into a list
  3. for temp in data:
  4. print temp

输出量

  1. a
  2. b
  3. c
  4. d
  5. e
  6. f
  7. g

2.分割+最大分割

仅按前2个空格分割。

  1. alphabet = "a b c d e f g"
  2. data = alphabet.split(" ",2) #maxsplit
  3. for temp in data:
  4. print temp

输出量

  1. a
  2. b
  3. c d e f g

3.用#分割

又一个例子。

  1. url = "mkyong.com#100#2015-10-1"
  2. data = url.split("#")
  3. print len(data) #3
  4. print data[0] # mkyong.com
  5. print data[1] # 100
  6. print data[2] # 2015-10-1
  7. for temp in data:
  8. print temp

输出量

  1. 3
  2. mkyong.com
  3. 100
  4. 2015-10-1
  5. mkyong.com
  6. 100
  7. 2015-10-1

参考

  1. Python内置类型

翻译自: https://mkyong.com/python/python-how-to-split-a-string/