【问题标题】:Print the words of the string and their length along the same time同时打印字符串的单词及其长度
【发布时间】:2022-01-28 11:33:59
【问题描述】:

希望大家身体健康……

一段时间以来,我一直在尝试获得我编写的代码之一的结果..但无法获得所需的结果...如果您能帮助我,我会非常高兴.. .☺☺

我有一个字符串,我需要同时打印字符串的单词及其长度,中间加一个冒号.....这是我的 code 这就是我需要的结果:

[这个:4 是:2 漂亮:6]

漂亮

但是当我尝试打印结果的第一行时弹出错误....

【问题讨论】:

    标签: python compiler-errors findbugs string-length


    【解决方案1】:

    试试这个:

    sentence = 'This is pretty'
    result = [f'{w}:{len(w)}' for w in sentence.split()]
    

    这是结果:

    >>> result
    ['This:4', 'is:2', 'pretty:6']
    

    【讨论】:

    • 嘿,Ricardo...谢谢大家帮助我...我已经按照您提到的那样更改了我的代码...这是代码 code.sololearn.com/cY7Ge74w7f7f/#py>,这是我的结果我得到.... ['This:4', 'is:2', 'pretty:6'] pretty 有没有办法让我得到这样的结果... ['This':4, 'is':2, 'pretty':6] 漂亮@Ricardo Bucco
    【解决方案2】:
    sent = "Hello Word!"
    
    print([f"{word}:{len(word)}" for word in sent.split()])
    

    【讨论】:

    • 你确实复制了我的解决方案
    【解决方案3】:
    word_count=[]
    for w in words:
        c = w + ":" + str(len(w)) 
        word_count.append(c)
    
    print(word_count)
    

    输出:

    ['This:4', 'is:2', 'pretty:6']
    

    【讨论】:

      【解决方案4】:

      您正在寻找这样的东西?

      sent = "This is pretty"
      words = sent.split(" ")
      print([word + ":"+str(len(word)) for word in words])
      #print(list(word,":",len(word)))
      
      length = [len(word) for word in words]
      maximum=max(length)
      text_index=length.index(maximum)
      longest_word=words[text_index]
      print(longest_word )
      
      

      输出:

      ['This:4', 'is:2', 'pretty:6']
      pretty
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-14
        • 1970-01-01
        • 2017-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多