Python3:修改列表字母大小写且不改动其他元素,lower()函数失效求助
lower() Not Working in Sublime Text for Python 3 Hey there! As someone who’s stumbled through Python’s early quirks, let’s break down why your lower() function might not be behaving as expected when converting uppercase letters to lowercase while keeping numbers intact. Here are the most common fixes to try:
1. You’re not capturing the returned value of lower()
Strings in Python are immutable—meaning lower() doesn’t modify the original string directly. It creates and returns a brand new lowercase string instead. A super common beginner mistake is forgetting to assign this new value back to a variable:
Wrong:
my_text = "HELLO123TEST" my_text.lower() # This creates a lowercase string but doesn't save it print(my_text) # Outputs HELLO123TEST (no change!)
Correct:
my_text = "HELLO123TEST" my_text = my_text.lower() # Assign the new lowercase string back print(my_text) # Outputs hello123test
Or you can directly print the result without reassigning:
print("HELLO123TEST".lower()) # Outputs hello123test
2. You’re working with non-string data types
If your input includes a mix of strings and numbers (like a list with both), calling lower() on non-string elements will cause errors, or if you’re applying it to the whole list instead of individual strings:
Wrong:
mixed_list = ["UPPERCASE", 456, "ANOTHERSTRING"] mixed_list.lower() # Throws an error—lists don't have a lower() method!
Correct:
Loop through the list and only apply lower() to string elements:
mixed_list = ["UPPERCASE", 456, "ANOTHERSTRING"] processed_list = [] for item in mixed_list: if isinstance(item, str): processed_list.append(item.lower()) else: processed_list.append(item) # Keep numbers as-is print(processed_list) # Outputs ['uppercase', 456, 'anotherstring']
3. Sublime Text is using the wrong Python version
Double-check that Sublime is running your code with Python 3, not Python 2 (which is outdated but might still be configured in some setups):
- Go to
Tools > Build System - Make sure
Python 3is selected (not justPython, which might default to Python 2)
Example Full Working Code
Here’s a complete snippet that handles both single strings and mixed data correctly:
# Single string conversion original_string = "PYTHON3ROCKS789" lowercase_string = original_string.lower() print("Single string result:", lowercase_string) # Mixed data conversion mixed_data = ["CODE", 123, "LEARN", 456, "PRACTICE"] result = [x.lower() if isinstance(x, str) else x for x in mixed_data] print("Mixed data result:", result)
Give these fixes a try—chances are one of them will solve your issue!
内容的提问来源于stack exchange,提问作者郭上阳

