[英]How can I multiply elements in a string using python and store resulting string in a variable?
Here is the Problem needed to be solved:这是需要解决的问题:
This problem requires you to create a output string from input string such that for every character in input string, there are three same characters in output string.('Hello' is the input sting) ("HHHeeellllllooo" is the desired output.) This problem requires you to create a output string from input string such that for every character in input string, there are three same characters in output string.('Hello' is the input sting) ("HHHeeellllllooo" is the desired output.)
This is what I have tried:这是我尝试过的:
input_string = "Hello"
output_string = ""
N = 3
for i in input_string:
strings = i * 3
print(strings, end = "")
How can I store the 'expanded' string to output_string?如何将“扩展”字符串存储到 output_string?
input_string = "Hello"
output_string = ""
N = 3
for i in input_string:
strings = i * 3
output_string += strings
print(output_string)
As far as I knew, inside the loop you only need to assign the value of by output_string += i * 3
instead of strings = i * 3
.据我所知,在循环内,您只需要分配 by
output_string += i * 3
而不是strings = i * 3
的值。 In this case you are keeping the pervious value, beside that you are also adding the new value to the pervious.在这种情况下,您将保留 pervious 值,此外,您还将新值添加到 pervious 中。 the new code will be like:
新代码将如下所示:
input_string = "Hello"
output_string = ""
N = 3
for i in input_string:
output_string += i * 3
print(output_string, end = "")
Instead of printing it, add it to output_string
.不要打印它,而是将它添加到
output_string
。
input_string = "Hello"
output_string = ""
N = 3
for i in input_string:
output_string += i * 3 # means same thing as output_string = output_string + i*3
print(output_string) # Output: HHHeeellllllooo
The key point here, is that you can use +
to concatenate strings:这里的关键点是您可以使用
+
来连接字符串:
a = "Hello, "
b = "World!"
a + b # Output: Hello, World!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.