如何对Python列表元素首尾去除'-'和'''?代码功能补充求助
- and ' from Words Got it, let's sort this out step by step. First, I spotted a critical issue in your original code: after splitting the text into a list of words with split(), you tried calling replace() directly on lines—but lists don't have a replace() method (that's a string method). That would throw an error immediately, so we need to fix that first.
For your actual requirement—stripping only the leading and trailing - and ' characters from each word while keeping those symbols (and others) in the middle—Python's str.strip() method is exactly what you need. It lets you specify a set of characters to remove exclusively from the start and end of a string.
Revised Code
# Use a context manager to safely open/read the file (auto-closes when done) with open(file, "r") as readfile: # Read text, convert to lowercase, split into individual words lines = readfile.read().lower().split() # Process each word: strip only leading/trailing '-' and "'", leave middle symbols intact processed_lines = [word.strip("'-") for word in lines]
How This Works
- Context Manager (
with open(...)): This is better practice than manually opening/closing files—it ensures the file is properly closed even if an error occurs. strip("'-"): This method removes any combination of-and'from the start and end of each word. Here's how it handles your examples:"-hi-"→"hi"(both leading and trailing-are removed)"'hi"→"hi"(leading'is removed)"safety-dance"→"safety-dance"(the-is in the middle, so it stays)"i'll"→"i'll"(the'is in the middle, so it stays)
If you still need to remove other special characters (like the ones in your original elements string) but only after stripping the -/', you could add an extra step—but based on your examples, it sounds like you want to preserve all middle symbols, so this code should fit your needs perfectly.
内容的提问来源于stack exchange,提问作者guide

