【问题标题】:How do i apply a ljust() transformation to every element of a string list?如何将 ljust() 转换应用于字符串列表的每个元素?
【发布时间】:2019-08-08 10:04:26
【问题描述】:

我正在学习 python,我正在尝试在一些示例文本的每一行前面添加 2 **。但是,当我在每个元素上调用 ljust(2,'*') 时,它不会更改原始字符串。我想用这个旧字符串替换新元素,但是如何?

这是我尝试过的。首先,我使用常规的 for 循环尝试了它,但没有奏效。然后我遇到了一个问题,其中解释了列表推导 Perform a string operation for every element in a Python list 所以我尝试了。

这就是我现在拥有的

example_string = '''hello there how are you doing!
i am doig well thank you
lets get to work!!! '''


def modify_example_string():
    global example_string
    new_string_list = [element.ljust(2,'*') for element in example_string.split('\n')]
    example_string = '\n'.join(new_string_list)
    print(new_string_list)

modify_example_string()

这应该返回一个包含所有 ljust 转换的新列表,但它没有,所以我想知道解决这个问题的正确方法。

【问题讨论】:

  • 另外,我想知道为什么列表理解在这种情况下不起作用
  • ljust(2,"**") 如果小于 2,将用 * 填充,而不是在每个字符串中添加 **
  • @tobias_k automatetheboringstuff.com/chapter6 >>> 'Hello'.rjust(20, '*') 根据书给出 '***************Hello'
  • 是的,你数了吗?那些是 20 *?

标签: python python-3.x


【解决方案1】:

您似乎误解了ljust(2, '*') 在做什么。它不会在字符串的开头添加两个*,但会用* 填充字符串的总长度为2。你所有的行都更长,所以它什么都不做。

相反,只需使用"**" + line 将星号添加到行中。

def modify_example_string():
    global example_string
    example_string = "\n".join("**" + line for line in example_string.splitlines())

另外,我建议不要使用global,而是使用参数和返回值:

def prepend_stars(s):
    return "\n".join("**" + line for line in s.splitlines())

example_string = prepend_stars(example_string)

【讨论】:

    【解决方案2】:

    ljust 方法不符合您的预期。 documentation 说:

    返回长宽的字符串左对齐的字符串。使用指定的 fillchar 完成填充(默认为 ASCII 空格)。 如果宽度小于等于len(s),则返回原始字符串

    您的列表理解是正确的。

    一种解决方案可能是使用format。很好的教程here

    带有format的示例代码:

    example_string = '''hello there how are you doing!
    i am doig well thank you
    lets get to work!!! '''
    
    
    def modify_example_string(example_string, ch, n):
        new_string_list = ["{} {}".format(ch * n, element)
                           for element in example_string.split('\n')]
        example_string = '\n'.join(new_string_list)
        return example_string
    
    print(modify_example_string(example_string, "*", 2))
    # ** hello there how are you doing!
    # ** i am doig well thank you
    # ** lets get to work!!!
    

    【讨论】:

      【解决方案3】:

      我会使用splitlines() 方法拆分您的字符串,并使用for 循环遍历这些行并构建一个新的连接字符串以用于输出。

      类似这样的:

      example_string = '''hello there how are you doing!
      i am doig well thank you
      lets get to work!!! '''
      
      
      def modify_example_string(input_string):
          new_string_list = ''
          for line in input_string.splitlines():
              new_string_list += f'**{line}\n'
          return new_string_list
      
      print(modify_example_string(example_string))
      

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 2019-12-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        • 2011-01-08
        • 1970-01-01
        相关资源
        最近更新 更多