Python实现驼峰式CSS属性转短横线分隔格式
Hey there! Let's break down how to solve your problem step by step—first writing the getIndices function to find uppercase letter positions, then converting those camelCase properties to standard kebab-case CSS.
1. Write the getIndices Function
This function will iterate through your string, check each character, and collect the indices of any uppercase letters.
def getIndices(s): uppercase_indices = [] for index, char in enumerate(s): if char.isupper(): uppercase_indices.append(index) return uppercase_indices
Test It Out
Using your sample string:
sample_str = 'borderRadius: 0px, zIndex: 2, transform: translate(170px, 195px) skew(-30deg, 0deg), fontSize:30px' print(getIndices(sample_str)) # Output: [6, 20, 53, 63]
These indices point to the R in borderRadius, I in zIndex, and S in fontSize respectively.
2. Convert CamelCase to Standard CSS Format
Once you have the uppercase indices, you can convert each uppercase letter to -[lowercase letter]. We'll iterate backwards through the indices to avoid shifting positions after replacements (since replacing a character adds length to the string, which would throw off later indices if we went left to right).
def camel_to_kebab_css(s): indices = getIndices(s) # Iterate in reverse to prevent index shifting from earlier replacements for idx in reversed(indices): s = s[:idx] + '-' + s[idx].lower() + s[idx+1:] return s # Test the conversion print(camel_to_kebab_css(sample_str))
This will output the standard CSS format you need:
border-radius: 0px, z-index: 2, transform: translate(170px, 195px) skew(-30deg, 0deg), font-size:30px
Bonus: More Efficient Regex Approach
If you don't need to explicitly get the indices (just want the conversion), a regex one-liner is cleaner and faster:
import re def camel_to_kebab_css_regex(s): # Replace every uppercase letter with "-[lowercase version]" return re.sub(r'([A-Z])', lambda match: '-' + match.group(1).lower(), s) # Same result, less code! print(camel_to_kebab_css_regex(sample_str))
内容的提问来源于stack exchange,提问作者Horai Nuri

