为什么我的Hashtag python脚本转换器不起作用?

问题描述 投票:0回答:4

我正在研究此脚本,该脚本将使用字符串并将其转换为驼峰式主题标签。我遇到的问题是,每当我运行代码时,它都会无限期地运行,而我不确定为什么。

if s == "": # a constraint given by the problem
    return False
elif len(s) > 140: # a constraint given by the problem 
    return False
else:
    i = 0
    while i < len(s)+1:
        if s[i] == " ": # if there is a space the next character would be a letter, logically
            if s[i+1] != " ": # if the next character is a letter (not a space) it will capitalize it 
                s[i+1].upper()
    i += 1
    return "#" + s.replace(" ", "")
python camelcasing
4个回答
0
投票

这是我为您准备的内容:

def ht(s):
    if s == "": # a constraint given by the problem
        return False
    elif len(s) > 140: # a constraint given by the problem 
        return False
    else:
        l = ["#"+l if l else "" for l in s.split('\n')] # list of all lines, if line is empty, keep as is, else, add hastag
        return '\n'.join(l)

c = '''
print('hello')
a = 5
print(a*4)
'''

print(ht(c))

输出:

#print('hello')
#a = 5
#print(a*4)

0
投票

您陷入无限循环,因为i += 1位于循环之外。


0
投票
if s == "": # a constraint given by the problem
    return False
elif len(s) > 140: # a constraint given by the problem 
    return False
else:
    i = 0
    while i < len(s)+1:
        if s[i] == " ": # if there is a space the next character would be a letter, logically
            if s[i+1] != " ": # if the next character is a letter (not a space) it will capitalize it 
                s[i+1].upper()
        i += 1
    return "#" + s.replace(" ", "")

0
投票

即使您按照某些答案的建议适当缩进i += 1,这也永远行不通。您认为这样做是什么:

s[i+1].upper()

Python中的字符串是不可变的-您无法更改它们。这将以大写字母形式返回s[i+1],但不会更改s。即这是无人操作!

让我们看看是否可以通过最少的更改使您的代码正常工作:

def hash_camel(s):
    if s == "": # a constraint given by the problem
        return False

    if len(s) > 140: # a constraint given by the problem
        return False

    string = "#"
    i = 0

    while i < len(s):
        if s[i] == ' ':  # if there is a space, the next character could be a letter
            if s[i + 1].isalpha():  # if the next character is a letter, capitalize it
                string += s[i + 1].upper()

                i += 1  # don't process s[i + 1] again in the next iteration

        else:
            string += s[i]

        i += 1

    return string

if __name__ == "__main__":

    strings = [
        '',
        'goat',
        'june bug',
        'larry curly moe',
        'never   odd   or     even',

    ]

    for string in strings:
        print(hash_camel(string))

输出

> python3 test2.py
False
#goat
#juneBug
#larryCurlyMoe
#neverOddOrEven
>

如果我是从头开始编写的,那么我可以这样处理:

def hash_camel(s):
    if s == "" or len(s) > 140:  # constraints given by the problem
        return None  # it's data, not a predicate, return None

    words = s.split()

    return '#' + words[0] + ''.join(map(str.capitalize, words[1:]))
© www.soinside.com 2019 - 2024. All rights reserved.