我正在尝试编写一个函数,通过在单词之间使用空格来分解驼峰式大小写。如何检查char后面是否已经有空格?
def solution(s):
space = ' '
for chr in s:
if chr.isupper() == True:
new_str = s.replace(chr, space + chr)
return new_str
输入:
"camelCaseWord" # a word in camelCasing
输出:
"camel Case Word" # separated by spaces where word starts with capital leter
我的解只给出"camelCase Word"
您的解决方案不起作用,因为您总是使用基础s
作为"源代码":
s = "someWordWithCases"
将"W"
替换为" W"
并存储在new_str
中…然后把结果扔掉,用" C"
替换"C"
——再次使用原来的s
——"W"
又回来了,在它们之前没有添加空间。
通过添加来创建字符串是浪费的。字符串是不可变的,所以在创建新字符串后旧的字符串会被丢弃。
解决方案是将每个大写字母分割成一个列表,然后用空格连接列表元素:
你的最小修改:
def solution(s):
r = []
for chr in s:
# if chr is capital and ( r is empty OR the last one is not a space)
if chr.isupper() and (not r or r[-1] != " "):
# add space then the capital letter
r.append(" "+chr)
else:
# only add letter
r.append(chr)
return ''.join(r)
或者使用切片的版本:
def solution(s):
k = []
start = 0
for i,c in enumerate(s):
if c.isupper() and start != i:
k.append(s[start:i])
start = i
if c == " ":
k.append(s[start:i])
start = i+1
if i > start:
k.append(s[start:])
return ' '.join(k)
# some test cases are "more" then pure camelCaseSpelling
tests = ["startsLowerThenHasWords", "StartsCapitalThenHasWords",
" starts with spaces no capitals", " Has some Capitals",
"has Capitals ABC and Others that areNotCapitals"]
maxL = max(len(t) for t in tests)
for t in tests:
print(f"{t:<{maxL}} ==> {solution(t)}")
,
startsLowerThenHasWords ==> starts Lower Then Has Words
StartsCapitalThenHasWords ==> Starts Capital Then Has Words
starts with spaces no capitals ==> starts with spaces no capitals
Has some Capitals ==> Has some Capitals
has Capitals ABC and Others that areNotCapitals ==> has Capitals A B C and Others that are Not Capitals
这个怎么样?我使用enumerate
来获取迭代的索引。
def solution(s):
space = ' '
space_positions = []
for index, chr in enumerate(s):
print(chr)
if chr != space and chr.isupper() == True:
if s[index - 1] != space:
space_positions.insert(0, index)
for index in space_positions:
s = s[:index] + " " + s[index:]
return s