How to append string in Python


Python

In this tutorial we will learn to append strings using multiple methods in Python programming. There are different operators and functions available in Python which can be used to concatenate strings, although if your have a long queue in a loop then the performance would matter.

 

How to append string in Python

Python version in my environment

# python3 --version
Python 3.6.8

 

Method 1: Using + operator

We used + operator earlier to print variables with strings. Well the same logic applies here. We intend to append two different variables into an existing string
In this example I have defined two variables with age contains integer while name contains string value

#!/usr/bin/env python3

# Define variable
age = 32
name = 'Deepak'

# Add variables with string
print('My name is ' + name + ' and I am ' + str(age) + ' years old.')

Now I have used + operator to concatenate variable value with string. Since age is an integer, I had to use str() to change the variable type to string

Output:

# python3 /tmp/append_string.py
My name is Deepak and I am 32 years old.

This operator usage can be tedious if you have a long range of strings to append. But for simple use cases as above, this operator would be useful.

 

Method 2: Using format string

  • We also used format string to concatenate strings and variables
  • You embed variables inside a string by using a special {} sequence and then put the variable you want inside the {} characters.
  • You also must start the string with the letter f for "format," as in f"Hello {somevar}".
  • In the same python script we used in the above method, now we will use format string
#!/usr/bin/env python3

# Define variable
age = 32
name = 'Deepak'

# Add variables with string
print('My name is {} and I am {} years old.'.format(name, age))

The output from this script:

# python3 /tmp/append_string.py
My name is Deepak and I am 32 years old.

 

Method 3: Using += Operator

  • We can also use += operator which would append strings at the end of existing value also referred as iadd
  • The expression a += b is shorthand for a = a + b, where a and b can be numbers, or strings, or tuples, or lists (but both must be of the same type).
  • In this example I have defined an empty global variable a and I will append a range of strings (integers would be marked as string using str()) into this variable
#!/usr/bin/env python3

# Define variable with empty string value
a = ''

for i in range(5):
    # append strings to the variable
    a += str(i)

# print variable a content
print(a)

The output from this python script would print a range from 0-4 which were stored in variable a

# python3 /tmp/append_string.py
01234

 

Method 4: Using str.join()

  • The join() method is useful when you have a list of strings that need to be joined together into a single string value.
  • The join() method is called on a string, gets passed a list of strings, and returns a string.
  • The returned string is the concatenation of each string in the passed-in list.
  • A TypeError will be raised if there are any non-string values in iterable, including bytes objects.

In this example I will join variable a and b with a white space character as the separator

#!/usr/bin/env python3

a = 'Hello'
b = 'World'
res = " ".join((a, b))
print(res)

Output:

# python3 /tmp/append_string.py
Hello World

Remember that join() is called on a string value and is passed a list value.

#!/usr/bin/env python3

# Define variable
a = ['1', '2', '3']

# string join() calls on is inserted between
# each string of the list argument.
res = " ".join((a))

# Print the Result
print(res)

The output from this script:

# python3 /tmp/append_string.py
1 2 3

 

Conclusion

In this tutorial we learned about how we can append and concatenate strings to each other using different methods in Python programming language. The choice of method would vary on requirement as if you have a long queue of strings to be joined then you must check the performance impact to make sure your system resources are not over utilized.
But for basic append string you can use any of these methods.

Lastly I hope this tutorial to append strings in Python was helpful. So, let me know your suggestions and feedback using the comment section.

Deepak Prasad

Deepak Prasad

Deepak Prasad is the founder of GoLinuxCloud, bringing over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, Networking, and Security. His extensive experience spans development, DevOps, networking, and security, ensuring robust and efficient solutions for diverse projects.

Certifications and Credentials:

  • Certified Kubernetes Application Developer (CKAD)
  • Go Developer Certification
  • Linux Foundation Certified System Administrator (LFCS)
  • Certified Ethical Hacker (CEH)
  • Python Institute PCAP (Certified Associate in Python Programming)
You can connect with him on his LinkedIn profile and join his Facebook and LinkedIn page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment