Python - 按自定义长度拆分字符串
给定一个字符串,根据自定义长度执行字符串拆分。
Input : test_str = ‘geeksforgeeks’, cus_lens = [4, 3, 2, 3, 1]
Output : [‘geek’, ‘sfo’, ‘rg’, ‘eek’, ‘s’]
Explanation : Strings separated by custom lengths.
Input : test_str = ‘geeksforgeeks’, cus_lens = [10, 3]
Output : [‘geeksforge’, ‘eks’]
Explanation : Strings separated by custom lengths.
方法#1:使用切片+循环
在这里,我们执行切片任务以满足自定义长度,并使用循环来迭代所有长度。
Python3
# Python3 code to demonstrate working of
# Multilength String Split
# Using loop + slicing
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing length list
cus_lens = [5, 3, 2, 3]
res = []
strt = 0
for size in cus_lens:
# slicing for particular length
res.append(test_str[strt : strt + size])
strt += size
# printing result
print("Strings after splitting : " + str(res))
Python3
# Python3 code to demonstrate working of
# Multilength String Split
# Using join() + list comprehension + next()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing length list
cus_lens = [5, 3, 2, 3]
# join() performs characters to string conversion
# list comprehension provides shorthand to solve problem
stritr = iter(test_str)
res = ["".join(next(stritr) for idx in range(size)) for size in cus_lens]
# printing result
print("Strings after splitting : " + str(res))
输出
The original string is : geeksforgeeks
Strings after splitting : ['geeks', 'for', 'ge', 'eks']
方法 #2:使用 join() + 列表推导 + next()
这是可以执行此任务的另一种方式。在这里,我们使用迭代器方法 next() 执行获取字符直到长度的任务,提供了更有效的解决方案。最后, join() 用于将每个字符列表转换为字符串。
蟒蛇3
# Python3 code to demonstrate working of
# Multilength String Split
# Using join() + list comprehension + next()
# initializing string
test_str = 'geeksforgeeks'
# printing original string
print("The original string is : " + str(test_str))
# initializing length list
cus_lens = [5, 3, 2, 3]
# join() performs characters to string conversion
# list comprehension provides shorthand to solve problem
stritr = iter(test_str)
res = ["".join(next(stritr) for idx in range(size)) for size in cus_lens]
# printing result
print("Strings after splitting : " + str(res))
输出
The original string is : geeksforgeeks
Strings after splitting : ['geeks', 'for', 'ge', 'eks']