Why result.append(words) wouldn't work


#1

I am wondering why result.append(words) wouldn't work.

as it resembles the format:

result.append(list) and not result.append(str)


Using Strings in Lists in Functions
#2

Because strings are immutable, we cannot append to them, so they don't need an append method.

Two options exist for us to mutate strings.

  1. Write the mutated string back onto ihe same variable, as in my_str = my_str + "xyz" (assumes my_str is at least defined by "" or some value), and
  2. Convert to a list, which is mutable, make the changes on the list, and join it back into a string.

my_str = "some text in a string"
print my_str
my_str = list(my_str)
print my_str
while " " in my_str:
    my_str.remove(" ")
print my_str
my_str = "".join(my_str)
print my_str

Console output

some text in a string
['s', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't', ' ', 'i', 'n', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']
['s', 'o', 'm', 'e', 't', 'e', 'x', 't', 'i', 'n', 'a', 's', 't', 'r', 'i', 'n', 'g']
sometextinastring

To do much the same thing on a string would involve building a new string from slices.

my_str = "some text in a string"
x = 0
while " " in my_str:
    y = my_str.index(' ')
    my_str = my_str[x:y] + my_str[y+1:]
print my_str

Console output

sometextinastring

#3

I thought that words wasn't a string and was a list. Am I not appending to a list when I used:

result.append(words) ? Basically, I don't understand how words is being detected as a string.


#4

words is a list, but result is a string.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.