- Python append string to line
- # Strip leading whitespace from Multiline string in Python
- # Proper indentation for multiline strings in Python
- # Add a backslash at the end of the first line
- # Close the multiline string on the same line
- # Ident or dedent the multiline string
- # Remove the empty lines at the beginning and end of the multiline string
- # Additional Resources
- How to append string in Python
- How to append string in Python
- Method 1: Using + operator
- Method 2: Using format string
- Method 3: Using += Operator
- Method 4: Using str.join()
- Conclusion
- Leave a Comment Cancel reply
- Python Tutorial
Python append string to line
In the example, we joined the strings in the list with a space separator.
However, you could also use a tab.
Copied!my_str = """\ First line Second line Third line """ result = "\t".join(line.strip() for line in my_str.splitlines()) print(repr(result)) # 👉️ "'First line\tSecond line\tThird line'"
# Strip leading whitespace from Multiline string in Python
Use the textwrap.dedent() method to strip the leading whitespace from a multiline string in Python.
The textwrap.dedent method will remove the common leading whitespace from every line of the string.
Copied!from textwrap import dedent from inspect import cleandoc multiline_str = """\ first second third""" # 👇️ remove indentation # first # second # third print(dedent(multiline_str)) # 👇️ removes indentation and empty lines at the beginning and end # first # second # third print(cleandoc(multiline_str))
The first example uses the textwrap.dedent method to remove the leading whitespace from the multiline string.
The textwrap.dedent method takes a multiline string and removes the common leading whitespace from every line of the string.
The method is used to display multiline strings that are indented in the source code without any indentation.
Note that we used a backslash at the end of the first line of the multiline string.
Copied!multiline_str = """\ first second third"""
If you don’t add the backslash, you’ll notice that an extra newline character gets added to the string.
Make sure to close the multiline string on the same line.
Copied!multiline_str = """\ first second third""" # 👈️ close on same line print(multiline_str)
If you don’t close the multiline string on the same line, an extra newline character gets added at the end of the string.
If your multiline string has empty lines at the beginning or end, use the inspect.cleandoc() method to remove them and remove the leading whitespace.
Copied!from inspect import cleandoc multiline_str = """ first second third """ # 👇️ removes indentation and empty lines at beginning and end # first # second # third print(cleandoc(multiline_str))
We didn’t use a backslash at the end of the first line of the string and didn’t close the multiline string on the same line, so the string has an empty line at the beginning and at the end.
The inspect.cleandoc() method takes care of removing the empty lines at the beginning and end and the leading whitespace.
If you don’t want to remove the empty lines at the beginning and end of the multiline string, use the textwrap.dedent() method.
# Proper indentation for multiline strings in Python
To properly indent multiline strings:
- Add a backslash at the end of the first line.
- Close the multiline string on the last line.
- Use the dedent() and indent() methods if you need to dedent or indent the multiline string.
Copied!from textwrap import dedent, indent from inspect import cleandoc multiline_str = """\ first second third""" # 👇️ with indentation # first # second # third print(multiline_str) # 👇️ without indentation # first # second # third print(dedent(multiline_str)) # 👇️ indent the multiline string a specific number of spaces # first # second # third print(indent(multiline_str, ' ')) # 👇️ using inspect.cleandoc # (removes empty lines at beginning and end, and leading whitespace) # first # second # third print(cleandoc(multiline_str))
# Add a backslash at the end of the first line
The first thing to note when using multiline strings is to add a backslash at the end of the first line.
Copied!multiline_str = """\ first second third""" print(multiline_str)
If you don’t add the backslash, you’ll notice that an extra newline character gets added to the string.
# Close the multiline string on the same line
Make sure to close the multiline string on the same line.
Copied!multiline_str = """\ first second third""" # 👈️ close on same line print(multiline_str)
If you don’t close the multiline string on the same line, an extra newline character gets added at the end of the string.
# Ident or dedent the multiline string
You can use the textwrap.indent() and textwrap.dedent() methods to indent or dedent the multiline string.
Copied!from textwrap import dedent, indent multiline_str = """\ first second third""" # 👇️ without indentation # first # second # third print(dedent(multiline_str)) # 👇️ indent the multiline string a specific number of spaces # first # second # third print(indent(multiline_str, ' '))
The textwrap.dedent method takes a multiline string and removes the common leading whitespace from every line of the string.
The method is used to display multiline strings that are indented in the source code without any indentation.
The textwrap.indent method takes a multiline string and a prefix and adds the prefix to the beginning of each line of the string.
By default, the method adds the prefix to the beginning of each line that doesn’t consist only of whitespace.
# Remove the empty lines at the beginning and end of the multiline string
You can also use the inspect.cleandoc method if you want to remove the empty lines at the beginning and end of the multiline string and the leading whitespace.
Copied!from inspect import cleandoc multiline_str = """ first second third """ # # first # second # third # print(multiline_str) # first # second # third print(cleandoc(multiline_str))
I intentionally didn’t add a backslash at the end of the first line and didn’t close the multiline string on the same line.
Notice that the inspect.cleandoc method removed the empty lines at the beginning and end of the string and removed the leading whitespace.
If you don’t want to remove the empty lines at the beginning and end of the multiline string, use the textwrap.dedent() method.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How to append string in 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
# 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 » .
- 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)
# 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.
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Leave a Comment Cancel reply
Python Tutorial
- Python Multiline Comments
- Python Line Continuation
- Python Data Types
- Python Numbers
- Python List
- Python Tuple
- Python Set
- Python Dictionary
- Python Nested Dictionary
- Python List Comprehension
- Python List vs Set vs Tuple vs Dictionary
- Python if else
- Python for loop
- Python while loop
- Python try except
- Python try catch
- Python switch case
- Python Ternary Operator
- Python pass statement
- Python break statement
- Python continue statement
- Python pass Vs break Vs continue statement
- Python function
- Python call function
- Python argparse
- Python *args and **kwargs
- Python lambda function
- Python Anonymous Function
- Python optional arguments
- Python return multiple values
- Python print variable
- Python global variable
- Python copy
- Python counter
- Python datetime
- Python logging
- Python requests
- Python struct
- Python subprocess
- Python pwd
- Python UUID
- Python read CSV
- Python write to file
- Python delete file
- Python any() function
- Python casefold() function
- Python ceil() function
- Python enumerate() function
- Python filter() function
- Python floor() function
- Python len() function
- Python input() function
- Python map() function
- Python pop() function
- Python pow() function
- Python range() function
- Python reversed() function
- Python round() function
- Python sort() function
- Python strip() function
- Python super() function
- Python zip function
- Python class method
- Python os.path.join() method
- Python set.add() method
- Python set.intersection() method
- Python set.difference() method
- Python string.startswith() method
- Python static method
- Python writelines() method
- Python exit() method
- Python list.extend() method
- Python append() vs extend() in list
- Create your first Python Web App
- Flask Templates with Jinja2
- Flask with Gunicorn and Nginx
- Flask SQLAlchemy