I want to join strings
my_string = "I am good."
such that it should be printing the same my_string 3 times, as in
my_string*3
with a space in between each full sentence. How do I do it? something like str.join(' ',my_string*3)
?
I know this a basic question, but I want to know this.
Thank you in advance, Sammed
Method 1: String Concatenation using + Operator It's very easy to use the + operator for string concatenation. This operator can be used to add multiple strings together.
Dart – Concatenate a String with itself Multiple Times To concatenate a string with itself multiple times in Dart, use Multiplication Operator * and pass the string and the integer as operands to it.
To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.
To concatenate to a string in a for loop: Declare a variable and initialize it to an empty string. Use a for loop to iterate over the sequence. Reassign the variable to its current value plus the current item.
You're pretty close. Try this:
>>> my_string = "I am good."
>>> " ".join([my_string]*3)
'I am good. I am good. I am good.'
You need [my_string]*3
instead of my_string*3
because you want a list containing the string three times (that can then be joined) instead of having a single big string containing the message three times.
Also, " ".join(a)
is shorthand for str.join(" ", a)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With