📜  Python|字符串拆分,包括空格

📅  最后修改于: 2022-05-13 01:54:43.558000             🧑  作者: Mango

Python|字符串拆分,包括空格

在使用Python字符串时,列表拆分的问题和应用非常普遍。在用例中,这些空格通常会被忽略。但有时,我们可能不需要省略空格,而是将它们包含在我们的编程输出中。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用split() + 列表推导

可以使用拆分函数和列表推导来执行这种操作。不省略空格的主要区别在于,我们在每个元素之后专门添加了我们可能在过程中省略的空格。

# Python3 code to demonstrate
# String Split including spaces
# using list comprehension + split()
  
# initializing string
test_string = "GfG is Best"
  
# printing original string
print("The original string : " + str(test_string))
  
# using list comprehension + split()
# String Split including spaces
res = [i for j in test_string.split() for i in (j, ' ')][:-1]
  
# print result
print("The list without omitting spaces : " + str(res))
输出 :
The original string : GfG is Best
The list without omitting spaces : ['GfG', ' ', 'is', ' ', 'Best']

方法#2:使用zip() + chain() + cycle()

也可以使用上述 3 个功能的组合来执行此特定任务。 zip函数可用于绑定逻辑,链和循环函数执行在适当位置插入空格的任务。

# Python3 code to demonstrate
# String Split including spaces
# using zip() + chain() + cycle()
from itertools import chain, cycle
  
# initializing string
test_string = "GfG is Best"
  
# printing original string
print("The original string : " + str(test_string))
  
# using zip() + chain() + cycle()
# String Split including spaces
res = list(chain(*zip(test_string.split(), cycle(' '))))[:-1]
  
# print result
print("The list without omitting spaces : " + str(res))
输出 :
The original string : GfG is Best
The list without omitting spaces : ['GfG', ' ', 'is', ' ', 'Best']