How to copy a string in Python

11 Answers

0 votes
# Copy using simple assignment

src = "Programming is fun"

dest = src # Copies reference only

print(dest)



'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz
0 votes
# Copy using slicing

src = "Programming is fun"

dest = src[:]

print(dest)



'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz
0 votes
# Copy using str() constructor

src = "Programming is fun"

dest = str(src)

print(dest)



'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz
0 votes
# Copy using f-string

src = "Programming is fun"

dest = f"{src}"

print(dest)



'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz
0 votes
# Copy using format()

src = "Programming is fun"

dest = "{}".format(src)

print(dest)



'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz
0 votes
# Copy using percent formatting

src = "Programming is fun"

dest = "%s" % src

print(dest)



'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz
0 votes
# Copy using join() on characters

src = "Programming is fun"

dest = "".join(list(src))

print(dest)



'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz
0 votes
# Copy using list conversion and join

src = "Programming is fun"

chars = list(src)

dest = "".join(chars)

print(dest)




'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz
0 votes
# Copy using manual loop

src = "Programming is fun"
dest = ""

for ch in src:
    dest += ch

print(dest)



'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz
0 votes
# Copy using bytearray round-trip

src = "Programming is fun"

dest = bytearray(src, "utf-8").decode("utf-8")

print(dest)



'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz
0 votes
# Copy using encode/decode

src = "Programming is fun"

dest = src.encode("utf-8").decode("utf-8")

print(dest)




'''
run:

Programming is fun

'''

 



answered 2 days ago by avibootz

Related questions

6 answers 19 views
7 answers 19 views
8 answers 27 views
8 answers 24 views
7 answers 19 views
...