检查字符串中的字符后面是否有 space

Check if character in string has space behind

我正在尝试编写一个函数,通过在单词之间使用 space 来分解驼峰式大小写。如何检查 char 后面是否已经有 space?

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"

这个怎么样?我使用 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

希望对您有所帮助。

您的解决方案不起作用,因为您总是使用基数 s 作为“来源”:

s = "someWordWithCases" 

将用 " W" 替换 "W" 并将其存储在 new_str 中......然后丢弃该结果并将 "C" 替换为 " C" - 使用原来的 s 又回来了 - "W" 又回来了,前面没有添加 space。


通过添加来创建字符串是一种浪费。字符串是不可变的,因此创建新字符串后旧字符串将被丢弃。

解决方法是将大写字母拆分成一个列表,然后用spaces:

加入列表元素

你的改动很小:

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