You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现驼峰式CSS属性转短横线分隔格式

Convert CamelCase CSS Properties to Standard Format + Get Uppercase Indices

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:44:17