将下面代码转换成python代码:
时间: 2023-11-06 21:04:41 浏览: 68
这是一个JavaScript代码,将一个字符串中的每个单词的首字母大写,其他字母小写,并返回新的字符串。
```
function capitalize(str) {
var words = str.split(' ');
for (var i = 0; i < words.length; i++) {
var letters = words[i].split('');
letters[0] = letters[0].toUpperCase();
for (var j = 1; j < letters.length; j++) {
letters[j] = letters[j].toLowerCase();
}
words[i] = letters.join('');
}
return words.join(' ');
}
```
以下是相应的Python代码:
```
def capitalize(str):
words = str.split(' ')
for i in range(len(words)):
letters = list(words[i])
letters[0] = letters[0].upper()
for j in range(1, len(letters)):
letters[j] = letters[j].lower()
words[i] = ''.join(letters)
return ' '.join(words)
```
阅读全文