📜  Python – 来自字符串的增量大小块

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

Python – 来自字符串的增量大小块

给定一个字符串,将其拆分为增量大小的连续列表。

方法#1:使用循环+切片

在此,我们使用字符串切片执行获取块的任务,并在迭代期间不断增加块大小。

Python3
# Python3 code to demonstrate working of 
# Incremental Size Chunks from Strings
# Using loop + slicing
  
# initializing string
test_str = 'geekforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
res = []
idx = 1
while True:
    if len(test_str) > idx:
          
        # chunking
        res.append(test_str[0 : idx])
        test_str = test_str[idx:]
        idx += 1
    else:
        res.append(test_str)
        break
      
# printing result 
print("The Incremental sized Chunks : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Incremental Size Chunks from Strings
# Using generator + slicing 
  
# generator function 
def gen_fnc(test_str):
    strt = 0
    stp = 1
    while test_str[strt : strt + stp]:
          
        # return chunks runtime while looping
        yield test_str[strt : strt + stp]
        strt += stp
        stp += 1
  
# initializing string
test_str = 'geekforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# calling fnc.
res = list(gen_fnc(test_str))
      
# printing result 
print("The Incremental sized Chunks : " + str(res))


输出
The original string is : geekforgeeks is best for geeks
The Incremental sized Chunks : ['g', 'ee', 'kfo', 'rgee', 'ks is', ' best ', 'for gee', 'ks']

方法#2:使用生成器+切片

在此,我们按照上述方法执行切片,不同之处在于块是使用生成器表达式渲染的,每个块在运行时循环生成。

Python3

# Python3 code to demonstrate working of 
# Incremental Size Chunks from Strings
# Using generator + slicing 
  
# generator function 
def gen_fnc(test_str):
    strt = 0
    stp = 1
    while test_str[strt : strt + stp]:
          
        # return chunks runtime while looping
        yield test_str[strt : strt + stp]
        strt += stp
        stp += 1
  
# initializing string
test_str = 'geekforgeeks is best for geeks'
  
# printing original string
print("The original string is : " + str(test_str))
  
# calling fnc.
res = list(gen_fnc(test_str))
      
# printing result 
print("The Incremental sized Chunks : " + str(res)) 
输出
The original string is : geekforgeeks is best for geeks
The Incremental sized Chunks : ['g', 'ee', 'kfo', 'rgee', 'ks is', ' best ', 'for gee', 'ks']