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

求助:实现单词首字母大写的JS函数并转为Python版本

Convert JavaScript Title-Casing Function to Python

Got it, let's turn that JavaScript word capitalization function into a Python equivalent! Based on your example input ('the quick brown fox') and expected output ('The Quick Brown Fox'), here are two solid approaches:

1. Use Python's Built-in str.title() Method

Python has a handy built-in string method that does exactly what you need out of the box:

def title_case(input_str):
    return input_str.title()

# Test with your example
sample_input = 'the quick brown fox'
print(title_case(sample_input))  # Output: 'The Quick Brown Fox'

This method is concise and works great for basic cases. Just note that it will capitalize the first letter of every word, including parts of contractions (e.g., "don't" becomes "Don'T"). If you need to handle edge cases like that, the next method gives you more control.

2. Manual Implementation for Customization

If you want finer control over how each word is processed, you can split the string, capitalize each word individually, then join them back together:

def title_case(input_str):
    # Split the string into individual words
    words = input_str.split()
    # Capitalize the first letter of each word, lowercase the rest
    capitalized_words = [word[0].upper() + word[1:].lower() for word in words]
    # Join the words back into a single string
    return ' '.join(capitalized_words)

# Test the function
sample_input = 'the quick brown fox'
print(title_case(sample_input))  # Output: 'The Quick Brown Fox'

This approach lets you tweak the logic—for example, if you need to skip capitalizing small words like "the" or "and" in certain contexts, you can add a check for those within the list comprehension.

内容的提问来源于stack exchange,提问作者MassMusing

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:35:14