Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

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. Here is a little snippet into what the output would ideally look like:

Input (min for length is 3) :

string = 'ABCDEFGHI'

Output:

['ABCDEFGHI', 'BCDEFGH', 'CDEFG']

I would be grateful for any guidance/advice!

question from:https://stackoverflow.com/questions/65948133/how-to-consistently-slice-the-first-and-last-character-of-a-string-in-python-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

>>> [string[i:len(string)-i] for i in range(3)]
['ABCDEFGHI', 'BCDEFGH', 'CDEFG']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...