简体   繁体   中英

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 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?

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 . In this case you are keeping the pervious value, beside that you are also adding the new value to the 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 .

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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