last modified July 29, 2022 Show
Python add string tutorial shows how to concatenate strings in Python. Python tutorial is a comprehensive tutorial on Python language. In Python, a string is an ordered sequence of Unicode characters. There are several ways of adding strings in Python:
Python add strings with + operator The easiest way of concatenating strings is to use the add_string.py #!/usr/bin/python a = 'old' b = ' tree' c = a + b print(c) Two strings are added using the $ ./add_string.py old tree In the second example, we use the compound addition operator. add_string2.py #!/usr/bin/python msg = 'There are' msg += ' three falcons' msg += ' in the sky' print(msg) The example builds a message with the $ ./add_string2.py There are three falcons in the sky Python add strings with join The string add_string_join.py #!/usr/bin/python msg = ' '.join(['There', 'are', 'three', 'eagles', 'in', 'the', 'sky']) print(msg) In the example, we form a message by joining seven words. The words are joined with a single space character. $ ./add_string_join.py There are three eagles in the sky Python add strings with string formatting We can build Python strings with string formatting. The variables are
expanded in the format_str.py #!/usr/bin/python w1 = 'two' w2 = 'eagles' msg = f'There are {w1} {w2} in the sky' print(msg) We build a message with Python's fstring. $ ./format_str.py There are two eagles in the sky Python add strings with __add_ method Another possibility to add strings is to use the special add_string3.py #!/usr/bin/python s1 = "and old" s2 = " falcon" s3 = s1.__add__(s2) print(s3) The example adds two strings with In this tutorial, we have shown several ways to add strings in Python. Read Python tutorial or list all Python tutorials. IntroductionIn this tutorial, we will learn different ways to add elements to a list in Python. There are four methods to add elements to a List in Python.
|