Infinity Loop
Infinity Loop

Reputation: 165

Python: for loop iteration accumulate values in string variable

Say I have a for loop that iterates through the characters in a string one by one.

Ex:

string_x = "abc"
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)

The output gives me a, b, c one by one.

Now I want to group this back into a different string after I scramble it character by character. I already figured out how to scramble it, but I can't just append it back to a string inside the loop because it overrides the string value each iteration and only ends up with one character such as 'b'. I want the for loop to create a new string named string_y that can incrementally have new characters appended to it without overriding the whole string every loop iteration. Any ideas?

Upvotes: 0

Views: 22703

Answers (4)

CDtoday
CDtoday

Reputation: 59

Not pretty clear question, but I'll give it a try.

Since you didn't mention it, I'll just presume that you got something like a scrambled list like scrambled_list = ['c', 'a', 'b'].

I guess you're asking for something like ''.join(scrambled_list), which will give you 'cab'.

scrambled_list = ['c', 'a', 'b']
sep = ''
output = sep.join(scrambled_list)

print(output)
'cab'

the join() method of string returns a string concatenate by the seperater, so

'-'.join(scrambled_list) will gives you 'c-a-b'.

Upvotes: 2

Arpit
Arpit

Reputation: 109

In order to add letter b to an existing string_y suppose, you'll have to concatenate it to the existing string_y like

string_y = string_y + 'b'

or in the above loop, it would be

string_x = "abc"
string_y = ""
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)
     string_y = string_y + data

Since strings are immutable data types in Python, concatenating two strings together actually creates a third string which is the combination of the previous two. So it's more efficient to add the letters to a list and combine it into a string.

string_x = "abc"
stringlist = []
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)
     stringlist.append(data)
string_y = "".join(stringlist)

Upvotes: 0

Arun
Arun

Reputation: 1179

I think you are looking for this

string_x = "abc"
data = ""
for i in range (0, len(string_x)):
    data += str(string_x[i])
print(data)

output

abc

you can use += or data = data + str(string_x[i])

Upvotes: 2

Shai
Shai

Reputation: 114796

Try using += (as suggested by xzoert in his comment)

string_x = 'abc'
string_y = ''  # init to empty string
for c in string_x:
    string_y += c  # add a character to string_y
print string_y

Upvotes: 0

Related Questions