Reputation: 891
I have created an empty string:
s = ""
how can I append text to it? I know how to append something to a list like:
list.append(something)
but how one can append something to an empty string?
Upvotes: 2
Views: 46728
Reputation: 1124
ls = "sts"
temp = ""
for c in range(len(ls)-1, -1, -1):
temp += ls[c]
if(temp == ls):
print("Palindrome")
else:
print("not")
This line is your answer : temp += ls[c]
Upvotes: 0
Reputation: 7187
Python str's (strings) are immutable (not modifiable). Instead, you create a new string and assign to the original variable, allowing the garbage collector to eventually get rid of the original string.
However, array.array('B', string) and bytearray are mutable.
Here's an example of using a mutable bytearray:
#!/usr/local/cpython-3.3/bin/python
string = 'sequence of characters'
array = bytearray(string, 'ISO-8859-1')
print(array)
array.extend(b' - more characters')
print(array)
print(array.decode('ISO-8859-1'))
HTH
Upvotes: 1
Reputation: 102902
Strings are immutable in Python, you cannot add to them. You can, however, concatenate two or more strings together to make a third string.
>>> a = "My string"
>>> b = "another string"
>>> c = " ".join(a, b)
>>> c
"My string another string"
While you can do this:
>>> a = a + " " + b
>>> a
"My string another string"
you are not actually adding to the original a
, you are creating a new string object and assigning it to a
.
Upvotes: 4
Reputation: 3270
like this:
s += "blabla"
Please note that since strings are immutable, each time you concatenate, a new string object is returned.
Upvotes: 5
Reputation: 34166
The right name would be to concatenate a string to another, you can do this with the +
operator:
s = ""
s = s + "some string"
print s
>>> "some string"
Upvotes: 6