How to Fill an Empty String Which Has Already Been Created in Python

How to Fill an Empty String Which Has Already Been Created in Python

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

5 Answers

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"
1

like this:

s += "blabla"

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

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

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
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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.