繁体   English   中英

有人可以向我解释为什么 '\\n' 在与函数一起使用时没有注册吗?

[英]Can someone explain to me why '\n' doesn't register when it is used in with a function?

对于上下文,这是来自 HackerRank 的骆驼案例 #4 问题。

我得到了一个多字符串,例如test ...

test = '''S;M;plasticCup()
C;V;mobile phone
C;C;coffee machine
'''

我需要根据几个条件(不相关)来操纵它。 成功操作test ,我需要返回我自己的多行字符串output ,我正在尝试在下面完成。

def feeder(user_input):
    split_total = user_input.splitlines()
    output = ''
    for element in split_total:
        output += f"{camelCase(element)} \n"
        #camelCase()` is the user-defined function that applies the "several conditions" mentioned earlier
        #code snippet for camelCase() provided at bottom of the post, in case it matters
    return output
feeder(test)

但是,我的输出变量完全忽略了换行符\\n s?

'plastic cup \nmobilePhone \nCoffeeMachine'

是什么赋予了?

我试过换行符,它在这里工作吗?

chr_list = ['a', 'b', 'c']
output = ''
for element in chr_list:
    output += f"{element}\n"
print(output)

输出

a
b
c

驼峰式代码

def camelCase(user_input):
    split_ls = user_input.split(';')
    if (split_ls[0] == 'S'): #splitting
        index_of_upr, split_of_upr = [], []
        split_ls[2] = split_ls[2].replace('()', '') #remove method's ()
        for index, character in enumerate(split_ls[2]):
            if (character.isupper()):
                split_ls[2] = split_ls[2].replace(character, ' ' + character.lower())
        split_ls[2] = split_ls[2].strip()
        return split_ls[2]
    else: #combining
        split_ls[2] = split_ls[2].split(' ')
        for i in range(len(split_ls[2])):
            split_ls[2][i] = split_ls[2][i].title()
        if (split_ls[1] == 'C'): #class
            return ''.join(split_ls[2])
        else: #method,variable
            split_ls[2][0] = split_ls[2][0].lower()
            if (split_ls[1] == 'V'): #variable
                return ''.join(split_ls[2])
            else: #method
                return ''.join(split_ls[2]) + '()'

谢谢大家看我的代码:)

返回字符串或打印它是有区别的。

  • 打印它时, \\n字符确实显示为换行符
  • 使用函数的 return 语句,它会继续在字符串中显示为\\n ,直到您print(string)

这里的区别在于将结果视为原始字符串与打印。

查看原始字符串时, \\n新行被转义为\\n

'plastic cup \nmobilePhone \nCoffeeMachine'

而如果你打印它,它应该将\\n解释为打印到一个新行,给你这样的东西:

plastic cup 
mobilePhone 
CoffeeMachine

您的方法返回字符串。 您必须打印字符串才能查看新行。 这里:

print(feeder(test))

输出:

plastic cup 
mobilePhone 
CoffeeMachine 

Print 将评估新行字符并将其反映为这样。

希望这有帮助:) 干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM