不大写的nam的第一个字母

2024-10-03 15:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

要对像DeAnna这样的名称进行编码,请键入:

name = "de\aanna" 

以及

^{pr2}$

在这段代码中,\a将通常不大写的字母大写。你用什么代码来产生一个像"George von Trapp"这样的名字,我想在这里取消大写字母的大写字母?在


Tags: 代码name名称编码键入字母de大写字母
3条回答

What do you code to produce a name like "George von Trapp" where I want to uncapitalize a normally capitalized letter?

字母在Python中不会自动大写。在您的例子中,"de\aanna"(我认为您应该使用"de anna")是大写的,因为您对它调用了title()。如果我没有误解你的问题,你想要的只是禁用这种“自动大写”。在

只是不要打电话给title()

name = "George von Trapp"
print(name.lower())

为什么不直接运行你自己的函数呢?在

 def capitalizeName(name):
     #split the name on spaces
     parts = name.split(" ")

     # define a list of words to not capitalize
     do_not_cap = ['von']

     # for each part of the name,
     # force the word to lowercase
     # then check if it is a word in our forbidden list
     # if it is not, then go ahead and capitalize it
     # this will leave words in that list in their uncapitalized state
     for i,p in enumerate(parts):
          parts[i] = p.lower()
          if p.lower() not in do_not_cap:
              parts[i] = p.title()

      # rejoin the parts of the word
      return " ".join(parts)

do_not_cap列表的要点是,它允许您进一步定义不希望很容易大写的部分。例如,有些名称中可能有一个“de”,您可能不希望大写。在

下面是一个示例:

^{pr2}$

\a不大写字母-它是bell escape sequence。在

^{}只是将任何一组字母的第一个字母大写。因为钟不是字母,它和空格有相同的含义。以下内容产生等效资本:

name = "de anna"
print(name.title())

无论如何,python中没有大写/不大写的魔法字符。只要把名字写好就行了。如果您需要一个正确的和小写的版本,请稍后通过str.lower创建以后的

^{pr2}$

如果你真的想从"georg van trapp"(我只是假装关于\a的讨论已经结束)到"Georg van Trapp"-欢迎你来决定你正在模拟的语言的语义。在

  • 一个简单的方法是将每个单词大写,但修复一些已知的单词。在

    name = "georg van trapp"
    proper_name = name.title()
    proper_name.replace(' Von ', ' von ').replace(' Zu ', ' zu ').replace(' De ', ' de ')
    print(name, ':', proper_name)
    
  • 您也可以使用list-和循环方法来减少头痛:

    lc_words = ['von', 'van', 'zu', 'von und zu', 'de', "d'", 'av', 'af', 'der', 'Teer', "'t", "'n", "'s"]
    name = "georg van trapp"
    proper_name = name.title()
    for word in lc_words:
        proper_name = proper_name.replace(' %s ' % word.title(), ' %s ' % word)
    print(name, ':', proper_name)
    
  • 如果名称的格式为First Second byword Last,则除了倒数第二个单词外,可以将所有内容都大写:

    name = "georg fritz ferdinand hannibal van trapp"
    proper_name = name.title().split()  # gets you the *individual* words, capitalized
    proper_name = ' '.join(proper_name[:-2] + [proper_name[-2].lower(), proper_name[-1]])
    print(name, ':', proper_name)
    
  • 任何短于四个字母的单词(警告,某些名字不可行!!!)在

    name = "georg fritz theodores ferdinand markus hannibal von und zu trapp"
    proper_name = ' '.join(word.title() if len(word) > 3 else word.lower() for word in name.split())
    print(name, ':', proper_name)
    

相关问题 更多 >