I have two strings:
>>> a = "abcd"
>>> b = "xyz"
>>> c = a + b
>>> c
abcdxyz
How can I get abcd xyz
as a result instead when adding a
and b
?
Simply just add a space between the two strings:
a = "abcd"
b = "xyz"
c = a + " " + b # note the extra space concatenated with the other two
print c
this will give you
abcd xyz
You can use a function such as .join()
, but for something so short, that would seem almost counter-intuitive (and IMO "overkill"). Ie, first create a list with the two strings, then call a function with that list and use the return of that function in a print statement ... when you can just concatenate the needed space with the 2 strings. Seems semantically more clear too.
Based on: "Simple is better than complex." ( The Zen of Python "import this" )
You can use join to concatenate your strings together with your selected delimiter.
a = "abcd"
b = "xyz"
c = " ".join([a, b])
Python supports the string formatting operations and a template system (the latter is technically a simple but powerful class) as part of the string module. While the plus operator does its work, the lack of string formatting can influence a lot the readability of the code. A basic example for string formatting:
c = '%s %s' % (a, b)
Since Python 3.6, you can use f-strings to join two strings with ease. The code is more succinct and the variables are referenced directly within the context of the string.
a = 'hello'
b = 'world'
c = f'{a} {b}'
print(c)
The above code would output the following:
hello world
The .join()
function is still the way to go when you have many strings or where the number of strings may vary.
If you only need to print a space between the two, you can use this:
a = "hi"
b = "how r u"
print a,b
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.