简体   繁体   中英

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?

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 .

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"

like this:

s += "blabla"

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

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM