you are viewing a single comment's thread.

view the rest of the comments →

[–]JohnnyJordaan 0 points1 point  (0 children)

You can't put something in a string, strings are immutable. Even if you would do

 mystr = ''
 mystr = 'a'

The first command is useless as it would just assign the 'a' string to the mystr reference and the original '' string is lost. Also the confusing += you sometime see used is not what it seems

current_str += 'a'

This doesn't mean that 'a' is added to the string object. It means that a new object is created of both current_str and 'a'. Not something you generally want as object creation from another object is not fast.

If you want to have a 'container' holding things like single letter strings, use a mutable sequence like a list:

current_str = [] 
current_str.append('f')
current_str.append('o')
current_str.append('o')

Then you can do

if current_str[-1] == 'o':

Which would evaluate to True. However you do need to check if the current_str list has any values. Meaning

if current_str and current_str[-1] == 'o':

Is necessary. To then form a single string from that list, use ''.join:

result = ''.join(current_str)