我有一个字符串的名字,在这个例子中是"markus johansson".
我正在尝试编写一个使'm'和'j'大写的程序:
name = "markus johansson" for i in range(1, len(name)): if name[0] == 'm': name[0] = "M" if name[i] == " ": count = name[i] + 1 if count == 'j': name[count] = 'J'
我很确定这应该可行,但它给了我这个错误:
File "main.py", line 5 inname[0] = "M" TypeError: 'str' object does support item assignment
我知道有一个名为.title()的库函数,但我想做"真正的编程".
我该如何解决?
我想你想要达到的目标是:
from string import capwords capwords(name)
产量:
'Markus Johansson'
编辑:好的,我看到你要打开一扇门.这是低级别的实现.
''.join([char.upper() if prev==' ' else char for char,prev in zip(name,' '+name)])
>>> "markus johansson".title() 'Markus Johansson'
内置字符串方法是可行的方法.
编辑:我看到你想重新发明轮子.任何特殊原因?您可以选择任意数量的复杂方法,例如:
' '.join(j[0].upper()+j[1:] for j in "markus johansson".split())
标准库仍然是可行的方法.
string.capwords()
(定义于string.py
)# Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def". def capwords(s, sep=None): """capwords(s, [sep]) -> string Split the argument into words using split, capitalize each word using capitalize, and join the capitalized words using join. Note that this replaces runs of whitespace characters by a single space. """ return (sep or ' ').join(x.capitalize() for x in s.split(sep))
str.title()
(定义于stringobject.c
)PyDoc_STRVAR(title__doc__, "S.title() -> string\n\ \n\ Return a titlecased version of S, i.e. words start with uppercase\n\ characters, all remaining cased characters have lowercase."); static PyObject* string_title(PyStringObject *self) { char *s = PyString_AS_STRING(self), *s_new; Py_ssize_t i, n = PyString_GET_SIZE(self); int previous_is_cased = 0; PyObject *newobj = PyString_FromStringAndSize(NULL, n); if (newobj == NULL) return NULL; s_new = PyString_AsString(newobj); for (i = 0; i < n; i++) { int c = Py_CHARMASK(*s++); if (islower(c)) { if (!previous_is_cased) c = toupper(c); previous_is_cased = 1; } else if (isupper(c)) { if (previous_is_cased) c = tolower(c); previous_is_cased = 1; } else previous_is_cased = 0; *s_new++ = c; } return newobj; }
str.title()
在纯Python中class String(str): def title(self): s = [] previous_is_cased = False for c in self: if c.islower(): if not previous_is_cased: c = c.upper() previous_is_cased = True elif c.isupper(): if previous_is_cased: c = c.lower() previous_is_cased = True else: previous_is_cased = False s.append(c) return ''.join(s)
例:
>>> s = ' aBc dEf ' >>> import string >>> string.capwords(s) 'Abc Def' >>> s.title() ' Abc Def ' >>> s ' aBc dEf ' >>> String(s).title() ' Abc Def ' >>> String(s).title() == s.title() True