繁体   English   中英

短语中每个单词的首字母大写

[英]Upper case first letter of each word in a phrase

好的,我想弄清楚如何在 python 中输入这样的短语......

Self contained underwater breathing apparatus

输出这个...

SCUBA

这将是每个单词的第一个字母。 这与索引有关吗? 也许是一个 .upper 函数?

这是执行此操作的pythonic方法:

output = "".join(item[0].upper() for item in input.split())
# SCUBA

你去吧。 简短易懂。

LE :如果您有除空格以外的其他分隔符,则可以按单词拆分,如下所示:

import re
input = "self-contained underwater breathing apparatus"
output = "".join(item[0].upper() for item in re.findall("\w+", input))
# SCUBA

这是完成它的最快方法

input = "Self contained underwater breathing apparatus"
output = ""
for i in input.upper().split():
    output += i[0]
#here is my trial, brief and potent!
str = 'Self contained underwater breathing apparatus'
reduce(lambda x,y: x+y[0].upper(),str.split(),'')
#=> SCUBA

Pythonic 习语

  • 在 str.split() 上使用生成器表达式
  • 通过将 upper() 移动到循环外部的一个调用来优化内部循环。

执行:

input = 'Self contained underwater breathing apparatus'
output = ''.join(word[0] for word in input.split()).upper()

其它的办法

input = 'Self contained underwater breathing apparatus'

output = ''.join(item[0].capitalize() for item in input.split())
def myfunction(string):
    return (''.join(map(str, [s[0] for s in string.upper().split()])))

myfunction("Self contained underwater breathing apparatus")

返回SCUBA

另一种可能更容易让初学者理解的方法:

acronym = input('Please give what names you want acronymized: ')
acro = acronym.split() #acro is now a list of each word
for word in acro:
    print(word[0].upper(),end='') #prints out the acronym, end='' is for obstructing capitalized word to be stacked one below the other
print() #gives a line between answer and next command line's return

我相信你也可以通过这种方式完成它。

def get_first_letters(s):
    return ''.join(map(lambda x:x[0].upper(),s.split()))
s = "Self contained underwater breathing apparatus" 
for item in s.split():
    print item[0].upper()

一些列表理解爱:

 "".join([word[0].upper() for word in sentence.split()])

为什么没有人使用正则表达式? 在 JavaScript 中,我会使用正则表达式,所以我不需要使用循环,请在下面找到 Python 示例。

import re
input = "Self-contained underwater & breathing apparatus google.com"
output = ''.join(re.findall(r"\b(\w)", input.upper()))
print(output)
# SCUBAGC

请注意,上面的正则表达式/\\b(\\w)/g使用 \\b 单词边界和 \\w 单词,因此它将匹配字母数字单词字符和非单词字符之间的位置,例如“&”不匹配并且“ .com" "c" 匹配,并且 "s" 和 "c" 匹配 "self-contained"

使用前瞻和后视的替代正则表达式:

  • /(?!a\\s)\\b[\\w]|&/g不包括“ a ”并包括“&”
  • /(?<=\\s)[\\w&]|^./g任何单词字符和每个空格后的“&”。 这可以防止在 .com 上匹配“c”,但也可以防止在“self-contained”上匹配“c”

代码片段
正则表达式 1 、正则表达式 2 、正则表达式 3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM