[英]How to consistently slice the first and last character of a string in Python 3
I need help with writing a loop that can slice through a string, taking away the first and last character.我需要帮助编写一个可以切开字符串的循环,去掉第一个和最后一个字符。 I understand that the slice [0:-1] can target those two positions, but I need a way for it to iterate through the whole string.我知道切片 [0:-1] 可以针对这两个位置,但我需要一种方法来遍历整个字符串。 Here is a little snippet into what the output would ideally look like:以下是 output 的理想外观的小片段:
Input (min for length is 3):输入(长度的最小值为 3):
string = 'ABCDEFGHI'
Output: Output:
['ABCDEFGHI', 'BCDEFGH', 'CDEFG']
I would be grateful for any guidance/advice!我将不胜感激任何指导/建议!
Try this:尝试这个:
>>> [string[i:len(string)-i] for i in range(3)]
['ABCDEFGHI', 'BCDEFGH', 'CDEFG']
Here's a function you can use:这是您可以使用的 function:
def foo(string, limit=None):
output = [string]
i = 0
if limit == None:
while i < len(string) / 2 - 1:
output.append(output[-1][1:-1])
i += 1
else:
while i < limit - 1:
output.append(output[-1][1:-1])
i += 1
return output
The second parameter can be used to set a limit to the length of the array.第二个参数可用于设置数组长度的限制。 It is optional.它是可选的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.