【发布时间】: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