[英]How to capitalize first and last letters of each word in a Python string?
I want to write a python function so that the first and last letters of the words in a string will be capitalized.我想编写一个python函数,以便字符串中单词的第一个和最后一个字母大写。 The string contains lower case letters and spaces.该字符串包含小写字母和空格。 I was thinking of doing something like:我正在考虑做类似的事情:
def capitalize(s):
s.title()
s[len(s) - 1].upper()
return s
but that doesn't seem to work.但这似乎不起作用。 Any suggestions?有什么建议?
For example, the string "i like cats" should become "I LikE CatS"例如,字符串“我喜欢猫”应该变成“我喜欢猫”
Here's a nice one-liner.这是一个不错的单线。 (for you golfers :P) (对于你的高尔夫球手:P)
capEnds = lambda s: (s[:1].upper() + s[1:-1] + s[-1:].upper())[:len(s)]
It demonstrates another way to get around the problems when the input is 0 or 1 characters.当输入为 0 或 1 个字符时,它演示了另一种解决问题的方法。
It can easily be applied to a string to capitalize the individual words:它可以很容易地应用于字符串以将单个单词大写:
' '.join(map(capEnds, 'I like cats'.split(' ')))
'I LikE CatS'
def capitalize(s):
s, result = s.title(), ""
for word in s.split():
result += word[:-1] + word[-1].upper() + " "
return result[:-1] #To remove the last trailing space.
print capitalize("i like cats")
Output输出
I LikE CatS
Apply title()
to the whole string, then for each word in the string capitalize the last character and the append them back together.将title()
应用于整个字符串,然后将字符串中的每个单词的最后一个字符大写并将它们附加在一起。
Try using slicing.尝试使用切片。
def upup(s):
if len(s) < 2:
return s.upper()
return ''.join((s[0:-1].title(),s[-1].upper())))
Edit: since the OP edited in that he now needs this for every word in a string...编辑:因为 OP 编辑,他现在需要这个字符串中的每个单词......
' '.join(upup(s) for s in 'i like cats'.split())
Out[7]: 'I LikE CatS'
My take on a fun one-liner:我对一个有趣的单线的看法:
def cap_both(phrase):
return ' '.join(map(lambda s: s[:-1]+s[-1].upper(), phrase.title().split()))
Demo:演示:
>>> cap_both('i like cats')
'I LikE CatS'
>>> cap_both('a')
'A'
Here it's what we will do:这是我们将要做的:
So:所以:
0) 0)
words = "welcome to the jungle!" words =“欢迎来到丛林!”
1) 1)
>>> words= words.split()
2) 2)
>>> words = [capitalize(x) for x in words]
3) 3)
>>> words = " ".join(words)
4) 4)
def capitalize(word):
return word[0].capitalize() + word[1:-1] + word[-1].capitalize()
try this simple and easy to understand piece of code,试试这段简单易懂的代码,
st = 'this is a test string'
def Capitalize(st):
for word in st.split():
newstring = ''
if len(word) > 1:
word = word[0].upper() + word[1:-1] + word[-1].upper()
else:
word = word[0].upper()
newstring += word
print(word)
And than call the function as below,然后调用如下函数,
Capitalize(st)
A really old post but another fun one liner using list comprehension:一个非常古老的帖子,但另一个有趣的使用列表理解的班轮:
cap = lambda st: (" ").join([x.title().replace(x[-1], x[-1].upper()) for x in st.split()])
>>> cap("I like cats")
'I LikE CatS'
n=input("Enter the str: ") n=input("请输入字符串:")
for i in n.split():对于 n.split() 中的 i:
print(i[0].upper() +i[1:-1] +i[-1].upper(),end=' ')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.