Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - concatenate a string to itself, multiple times

Tags:

python

string

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

like image 530
sammed Avatar asked Jun 30 '11 22:06

sammed


People also ask

How do you concatenate a string multiple times in Python?

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.

How do you concatenate a string multiple times?

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.

How do you concatenate 3 strings in Python?

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.

How do I concatenate a string in a for loop?

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.


1 Answers

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).

like image 189
dhg Avatar answered Oct 15 '22 07:10

dhg