如何在Python中将字符串转换为标题大小写?

发布于 2024-12-19 13:26:09 字数 133 浏览 4 评论 0原文

是否有库或标准方法来执行此任务?

例子:

HILO -> Hilo
new york -> New York
SAN FRANCISCO -> San Francisco

Is there a library or standard way to perform this task?

Example:

HILO -> Hilo
new york -> New York
SAN FRANCISCO -> San Francisco

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

安静 2024-12-26 13:26:09

为什么不直接从文档中使用 title

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

如果你真的想要 PascalCase 你可以使用这个:

>>> ''.join(x for x in 'make IT pascal CaSe'.title() if not x.isspace())
'MakeItPascalCase'

Why not use title Right from the docs:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

If you really wanted PascalCase you can use this:

>>> ''.join(x for x in 'make IT pascal CaSe'.title() if not x.isspace())
'MakeItPascalCase'
网名女生简单气质 2024-12-26 13:26:09

这个总是以小写字母开头,并且还会删除非字母数字字符:

def camelCase(st):
    output = ''.join(x for x in st.title() if x.isalnum())
    return output[0].lower() + output[1:]

This one would always start with lowercase, and also strip non alphanumeric characters:

def camelCase(st):
    output = ''.join(x for x in st.title() if x.isalnum())
    return output[0].lower() + output[1:]
私藏温柔 2024-12-26 13:26:09
def capitalizeWords(s):
  return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)

re.sub 可以采用一个函数来进行“替换”(而不仅仅是一个字符串,这是大多数人似乎熟悉的用法)。对于模式的每个匹配,将使用 re.Match 对象调用此 repl 函数,并且结果(应该是字符串)将用作该匹配的替换。

同一事物的更长版本:

WORD_RE = re.compile(r'\w+')

def capitalizeMatch(m):
  return m.group(0).capitalize()

def capitalizeWords(s):
  return WORD_RE.sub(capitalizeMatch, s)

这会预编译模式(通常被认为是良好的形式)并使用命名函数而不是 lambda。

def capitalizeWords(s):
  return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)

re.sub can take a function for the "replacement" (rather than just a string, which is the usage most people seem to be familiar with). This repl function will be called with an re.Match object for each match of the pattern, and the result (which should be a string) will be used as a replacement for that match.

A longer version of the same thing:

WORD_RE = re.compile(r'\w+')

def capitalizeMatch(m):
  return m.group(0).capitalize()

def capitalizeWords(s):
  return WORD_RE.sub(capitalizeMatch, s)

This pre-compiles the pattern (generally considered good form) and uses a named function instead of a lambda.

揪着可爱 2024-12-26 13:26:09

潜在的库: https://pypi.org/project/stringcase/

示例:

import stringcase
stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"

虽然它是否是值得怀疑的会留下空格。(示例显示它删除了空格,但有一个错误跟踪器问题指出它留下了空格。)

Potential library: https://pypi.org/project/stringcase/

Example:

import stringcase
stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"

Though it's questionable whether it will leave spaces in. (Examples show it removing space, but there is a bug tracker issue noting that it leaves them in.)

献世佛 2024-12-26 13:26:09

只需使用 .title() ,它就会将每个单词的第一个字母转换为大写,其余为小写:

>>> a='mohs shahid ss'
>>> a.title()
'Mohs Shahid Ss'
>>> a='TRUE'
>>> b=a.title()
>>> b
'True'
>>> eval(b)
True

just use .title(), and it will convert first letter of every word in capital, rest in small:

>>> a='mohs shahid ss'
>>> a.title()
'Mohs Shahid Ss'
>>> a='TRUE'
>>> b=a.title()
>>> b
'True'
>>> eval(b)
True
江挽川 2024-12-26 13:26:09

为什么不写一个呢?像这样的东西可能会满足您的要求:

def FixCase(st):
    return ' '.join(''.join([w[0].upper(), w[1:].lower()]) for w in st.split())

Why not write one? Something like this may satisfy your requirements:

def FixCase(st):
    return ' '.join(''.join([w[0].upper(), w[1:].lower()]) for w in st.split())
春夜浅 2024-12-26 13:26:09

注意:为什么我要提供另一个答案? 这个答案基于问题的标题和驼峰命名的概念:一系列已连接的单词(没有空格) !)使得每个原始单词都以大写字母开头(其余为小写),除了该系列的第一个单词(完全小写)。还假设“所有字符串”指的是 ASCII 字符集; unicode 不适用于此解决方案)。

simple

鉴于上述定义,

import re
word_regex_pattern = re.compile("[^A-Za-z]+")

def camel(chars):
  words = word_regex_pattern.split(chars)
  return "".join(w.lower() if i is 0 else w.title() for i, w in enumerate(words))

调用此函数时,会导致这种方式

camel("San Francisco")  # sanFrancisco
camel("SAN-FRANCISCO")  # sanFrancisco
camel("san_francisco")  # sanFrancisco

不太简单。

请注意,当呈现已驼峰式大小写的字符串时,它会失败!

camel("sanFrancisco")   # sanfrancisco  <-- noted limitation

甚至更不简单

请注意,它会因许多 unicode 字符串而失败,

camel("México City")    # mXicoCity     <-- can't handle unicode

我没有针对这些情况的解决方案(或可以通过一些创造力引入的其他解决方案)。因此,就像所有与字符串有关的事情一样,请涵盖您自己的边缘情况,祝您使用 unicode 好运!

Note: Why am I providing yet another answer? This answer is based on the title of the question and the notion that camelcase is defined as: a series of words that have been concatenated (no spaces!) such that each of the original words start with a capital letter (the rest being lowercase) excepting the first word of the series (which is completely lowercase). Also it is assumed that "all strings" refers to ASCII character set; unicode would not work with this solution).

simple

Given the above definition, this function

import re
word_regex_pattern = re.compile("[^A-Za-z]+")

def camel(chars):
  words = word_regex_pattern.split(chars)
  return "".join(w.lower() if i is 0 else w.title() for i, w in enumerate(words))

, when called, would result in this manner

camel("San Francisco")  # sanFrancisco
camel("SAN-FRANCISCO")  # sanFrancisco
camel("san_francisco")  # sanFrancisco

less simple

Note that it fails when presented with an already camel cased string!

camel("sanFrancisco")   # sanfrancisco  <-- noted limitation

even less simple

Note that it fails with many unicode strings

camel("México City")    # mXicoCity     <-- can't handle unicode

I don't have a solution for these cases(or other ones that could be introduced with some creativity). So, as in all things that have to do with strings, cover your own edge cases and good luck with unicode!

回忆凄美了谁 2024-12-26 13:26:09
def camelCase(st):
    s = st.title()
    d = "".join(s.split())
    d = d.replace(d[0],d[0].lower())
    return d
def camelCase(st):
    s = st.title()
    d = "".join(s.split())
    d = d.replace(d[0],d[0].lower())
    return d
亣腦蒛氧 2024-12-26 13:26:09

我想为这篇文章添加我的一点贡献:

def to_camelcase(str):
  return ' '.join([t.title() for t in str.split()])

I would like to add my little contribution to this post:

def to_camelcase(str):
  return ' '.join([t.title() for t in str.split()])
帅气尐潴 2024-12-26 13:26:09

来自代码战争 - 在 Python 中为字符串编写简单的 .camelCase 方法。所有单词的第一个字母必须大写,不带空格。
驼峰(“你好”)=>哈罗案例
camelcase("驼峰式单词") =>驼峰式单词

def camel_case(string):
    titled_string = string.title()
    space_joined_string = titled_string.replace(' ', '')
    return space_joined_string

From code wars - Write simple .camelCase method in Python for strings. All words must have their first letter capitalized without spaces.
camelcase("hello case") => HelloCase
camelcase("camel case word") => CamelCaseWord

def camel_case(string):
    titled_string = string.title()
    space_joined_string = titled_string.replace(' ', '')
    return space_joined_string
长安忆 2024-12-26 13:26:09

这是一个例子:

def format_name(f_name,l_name):
    formated_f_name = f_name.title()
    formated_l_name = l_name.title()
    return f'{formated_f_name} {formated_l_name}'

print(format_name('GeOrGE', 'MADISON'))

>>> George Madison

Here is an example:

def format_name(f_name,l_name):
    formated_f_name = f_name.title()
    formated_l_name = l_name.title()
    return f'{formated_f_name} {formated_l_name}'

print(format_name('GeOrGE', 'MADISON'))

>>> George Madison
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文