How to concatenate two strings in PythonPython string is a collection of Unicode characters. Python provides many built-in functions for string manipulation. String concatenation is a process when one string is merged with another string. It can be done in the following ways.
Let’s understand the following string concatenation methods. Using + operatorThis is an easy way to combine the two strings. The + operator adds the multiple strings together. Strings must be assigned to the different variables because strings are immutable. Let’s understand the following example. Example – Output: Hello Devansh Explanation: In the above example, the variable str1 stores the string “Hello”, and variable str2 stores the “Devansh”. We used the + operator to combine these two string variables and stored in str3. Using join() methodThe join() method is used to join the string in which the str separator has joined the sequence elements. Let’s understand the following example. Example – Output: HelloJavaTpoint Hello JavaTpoint Explanation: In the above code, the variable str1 stores the string “Hello” and variable str2 stores the “JavaTpoint”. The join() method returns the combined string that is stored in the str1 and str2. The join() method takes only list as an argument. Using % OperatorThe % operator is used for string formatting. It can also be used for string concatenation. Let’s understand the following example. Example – Output: Hello JavaTpoint Explanation – In the above code, the %s represents the string data-type. We passed both variables’s value to the %s that combined the strings and returned the “Hello JavaTpoint”. Using format() functionPython provides the str.format() function, which allows use of multiple substitutions and value formatting. It accepts the positional arguments and concatenates the string through positional formatting. Let’s understand the following example. Example – Output: Hello JavaTpoint Hello JavaTpoint Explanation: In the above code, the format() function combines both strings and stores into the str3 variable. The curly braces {} are used as the position of the strings. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263614.html