Journey to CS/프로그래밍 언어

[파이썬] 문자열 조작 - strip() 메소드 예시 뜯어보기

Cordilog 2025. 2. 14. 17:27

 

[예시] 

>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS')
'BaconSpamEggs'

 

*Source: Automate the Boring Stuff with Python

 

[Breakdown by Perplexity]

 

Let me break this down for you step by step so you can understand the code and the result.

Code Explanation

  1. The strip() Method:
  2. The Input String:

 

spam = 'SpamSpamBaconSpamEggsSpamSpam'

This is a string containing multiple repetitions of "Spam", with "Bacon" and "Eggs" in between.

  1. The Argument to strip():

 

spam.strip('ampS')

Step-by-Step Execution

  1. The original string is:

 

'SpamSpamBaconSpamEggsSpamSpam'

  1. Starting from the beginning:
  2. Now we reach "BaconSpamEggsSpamSpam":
  3. Moving to the end of the string:
  4. After stripping both ends, we are left with:

 

'BaconSpamEggs'

Final Result

The result of spam.strip('ampS') is:

 

'BaconSpamEggs'

Key Takeaways

  1. strip() only removes characters from the start and end of a string, not from the middle.
  2. The argument to strip() ('ampS') specifies individual characters to remove, not a specific sequence.
  3. Characters are stripped until a character not in the specified set ('ampS') is encountered at either end.