2

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?

1
  • A better way than concatinating strings as you go is to keep all the parts in a list until you need the result and then do a single join (which then happens within the C code) i.e "".join(string_segments_list) Commented Jan 2, 2014 at 1:46

5 Answers 5

6

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, if you need to concatenate two strings. But one should use s.join([...]) for more.
5

like this:

s += "blabla"

Please note that since strings are immutable, each time you concatenate, a new string object is returned.

Comments

4

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.

2 Comments

so it is not possible to add text to it?
you can by concatenating - a = a + "some text" which will return a new object which is assigned to a.
1

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

1 Comment

Of course there's always the most resource demanding solution, not to mention the problems that arise if the string includes unicode characters.
0
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.