Python程序分割字符串为自定义长度
在本文中,我们将学习如何在python中按自定义长度分割字符串。
使用的方法
以下是完成此任务的各种方法:
使用for循环和切片
使用列表推导式、join()和next()函数
示例
假设我们已经获取了一个**输入字符串**和**自定义长度列表**。我们现在将使用上述方法根据输入的自定义长度分割输入字符串。
输入
inputString = 'hitutorialspoint' customLengths = [4, 1, 6, 5]
输出
['hitu', 't', 'orials', 'point']
在上面的示例中,首先根据给定的自定义长度分割输入列表:
4个字符 - 'hitu’
1个字符 - ‘r’
6个字符 - ‘orials’
5个字符 - ‘point
方法1:使用for循环和切片
算法(步骤)
以下是执行所需任务的算法/步骤:
创建一个变量来存储输入字符串。
打印输入字符串。
创建一个变量来存储输入的自定义长度列表。
创建一个空列表来存储结果列表。
将起始索引初始化为0。
使用**for循环**遍历自定义长度列表中的每个元素。
使用**append()**函数(在列表末尾添加元素)追加在给定索引之间切片的结果。
将起始索引的值增加自定义长度列表元素。
根据给定的自定义长度分割输入列表后,打印结果列表。
示例
以下程序使用for循环和切片,在根据给定的自定义长度分割输入列表后返回一个列表:
# input string
inputString = 'hitutorialspoint'
# printing input string
print("Input string: ", inputString)
# input custom lengths list
customLengths = [4, 1, 6, 5]
# empty list for storing a resultant list
outputList = []
# initializing start index as 0
startIndex = 0
# travsering through each element of the custom lengths list
for l in customLengths:
# appending the custom length string sliced from the
# starting index to the custom length element
outputList.append(inputString[startIndex: startIndex + l])
# Increment the start Index value with the custom length element
startIndex += l
# printing the resultant output list
print("Resultant list after splitting by custom lengths:\n", outputList)
输出
执行上述程序将生成以下输出:
Input string: hitutorialspoint Resultant list after splitting by custom lengths: ['hitu', 't', 'orials', 'point']
方法2:使用列表推导式、join()和next()函数
列表推导式
当您希望根据现有列表的值构建新列表时,列表推导式提供了一种更短/简洁的语法。
next()函数
返回迭代器(如列表、字符串元组等)中的下一个项目。如果可迭代对象到达其末尾,您可以添加一个默认返回值来返回。
语法
next(iterable, default)
**join()函数** - join()是Python中的一个字符串函数,用于连接由字符串分隔符分隔的序列元素。此函数连接序列元素以转换为字符串。
iter()函数
返回给定对象的迭代器。它创建一个每次迭代一个元素的对象。
语法
以下是函数的语法。
iter(object, sentinel)
参数
**object** - 此参数指定要创建其迭代器(列表、元组、集合等)的对象
**sentinel** - 它是一个表示序列结束的唯一值。
算法(步骤)
以下是执行所需任务的算法/步骤:
使用**iter()**函数返回输入字符串的迭代器(遍历字符串)
遍历customLengths列表中的每个元素,并使用next()和join()函数连接字符串的下一个l(迭代器值)个字符。
根据给定的自定义长度分割输入列表后,打印结果列表。
示例
以下程序使用列表推导式、join()和next()函数,在根据给定的自定义长度分割输入列表后返回一个列表:
# input string
inputString = 'hitutorialspoint'
# printing input string
print("Input string: ", inputString)
# input custom lengths list
customLengths = [4, 1, 6, 5]
# Getting the string as an iter object to iterate through it
stringitr = iter(inputString)
# traversing through each element of customLengths list and
# Joining the next l characters of the string
outputList = ["".join(next(stringitr) for i in range(l)) for l in customLengths]
# printing the resultant output list
print("Resultant list after splitting by custom lengths:\n", outputList)
输出
执行上述程序将生成以下输出:
Input string: hitutorialspoint Resultant list after splitting by custom lengths: ['hitu', 't', 'orials', 'point']
结论
在本文中,我们学习了如何使用两种不同的方法将给定的字符串分割成不同的长度。此外,我们还学习了如何使用iter()方法遍历字符串,以及如何使用next()函数获取最多n个字符的字符串。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP