[英]python slicing substrings or strings
If I have a string 'banana peel'
and I want to break it down to a width of 3 characters as in: 如果我有一个字符串
'banana peel'
并且想将其分解为3个字符的宽度,如下所示:
'ban'
'ana'
'pee'
'l'
How would I go about that? 我将如何处理? How would I remove the space/whitespace between 'banana' and 'peel' that is in the middle of the string and create the results above?
如何删除字符串中间的“香蕉”和“果皮”之间的空格/空白,并在上面创建结果?
Only things that come to mind are things like list()
and strip()
只有我想到的是
list()
和strip()
Just like this: 像这样:
string = "banana peel"
string = string.replace(" ", "")
results = []
for i in range(0, len(string), 3):
results.append(string[i:i + 3])
print(results)
replace(" ", "")
replaces all the spaces with nothing, giving bananapeel
. replace(" ", "")
替换所有空格,为bananapeel
。 range(0, len(string), 3)
will give a list of numbers from 0
to the length of the string with an interval of 3. Each set gets added to the array for you to print in the end. range(0, len(string), 3)
将给出一个从0
到字符串长度的数字列表,间隔为3。每组都添加到数组中,以便最终打印。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.