让我们接受2个字符串a
和b
,并使用+
通过print()函数将它们连接起来。
a = 'Hello'
b = 'World'
print(a + b, sep = ' ')
# prints HelloWorld
print(a + ' ' + b)
# prints Hello World
我有2个问题:
a)我可以使用sep在串联字符串a
和b
之间添加空格吗?
b)如果不是,那么是否还有其他方法可以在串联字符串a
和b
之间添加空格?
答案 0 :(得分:0)
如果您真的想使用加号将字符串与定界符连接起来。您可以使用加号先创建一个列表,然后应用将定界列表中参数的方法。
# So, let's make the list first
str_lst = [a] + [b] # you could also do [a, b], but we wanted to make use of the plus sign.
# now we can for example pass this to print and unpack it with *. print delimits by space by default.
print(*str_list) # which is the same as print(str_list[0], str_list[1]) or print(a, b), but that would not make use of the plus sign.
# Or you could use join the concetenate the string.
" ".join(*str_list)
好的,希望您今天学到了一些新知识。但是请不要这样做。这不是要这样做的意思。