如何在Python中按规则缩短字符串(含例外情况)
Python Chord Shortening Solution
Got it, let's figure out how to shorten those chord strings exactly as you need. The core idea is to keep the initial letter, plus any immediately following "m" or "is" suffix, and discard everything else afterward. Regular expressions are ideal here because they let us define this pattern clearly.
Here's a practical implementation:
import re def shorten_chord(chord): # Pattern breakdown: # ^([A-Ga-g]) → Match the first character (A-G, case-insensitive) # (m|is)? → Optionally match either "m" or "is" right after the initial letter match = re.match(r'^([A-Ga-g])(m|is)?', chord) if match: # Join the matched groups (ignoring None if no suffix was found) return ''.join(part for part in match.groups() if part) # Fallback: return the original string if it doesn't match our chord pattern return chord # Test with your examples test_cases = ["Em", "Bsus4", "F7", "Fis7"] for original in test_cases: shortened = shorten_chord(original) print(f"{original} → {shortened}")
Output:
Em → Em Bsus4 → B F7 → F Fis7 → Fis
How it works:
- The regex
^([A-Ga-g])(m|is)?targets exactly the parts we want to keep:- The first capture group grabs the initial chord letter (supports both uppercase and lowercase, though your examples use uppercase).
- The second optional capture group checks for either "m" or "is" immediately after the first letter.
- We join the captured parts together—if there's no "m" or "is", the second group will be
None, so we filter that out to avoid adding extra characters. - The fallback ensures we don't break any unexpected input that doesn't fit the chord pattern.
If you ever need to add more suffixes to keep (like "dim" or "aug"), just update the regex to include them: r'^([A-Ga-g])(m|is|dim|aug)?'—it's super flexible.
内容的提问来源于stack exchange,提问作者user11914084
相关产品推荐
相关产品推荐

