📜  Python – 多行字符串的水平连接

📅  最后修改于: 2022-05-13 01:54:23.224000             🧑  作者: Mango

Python – 多行字符串的水平连接

给定一对字符串,它是多行的,水平执行连接。

例子:

方法 #1:使用 zip() + split() + join() + 列表理解

在此,我们使用 split() 执行通过“\n”分割的任务,并使用 zip() 将它们配对在一起。下一步是使用“\n”和 join() 将两个压缩字符串连接到水平方向。

Python3
# Python3 code to demonstrate working of
# Horizontal Concatenation of Multiline Strings
# Using zip() + split() + join() + list comprehension
  
# initializing strings
test_str1 = '''
geeks 4
geeks'''
  
test_str2 = '''
is
best'''
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# split lines
splt_lines = zip(test_str1.split('\n'), test_str2.split('\n'))
  
# horizontal join
res = '\n'.join([x + y for x, y in splt_lines])
  
# printing result
print("After String Horizontal Concatenation : " + str(res))


Python3
# Python3 code to demonstrate working of
# Horizontal Concatenation of Multiline Strings
# Using map() + operator.add + join()
from operator import add
  
# initializing strings
test_str1 = '''
geeks 4
geeks'''
test_str2 = '''
is
best'''
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# using add to concat, map() to concat each lines zipped
res = '\n'.join(map(add, test_str1.split('\n'), test_str2.split('\n')))
  
# printing result
print("After String Horizontal Concatenation : " + str(res))


输出
The original string 1 is : 
geeks 4
geeks
The original string 2 is : 
is
best
After String Horizontal Concatenation : 
geeks 4is
geeksbest

方法 #2:使用 map() + 运算符.add + join()

在此,我们使用 map() 在 add() 的帮助下进行连接,split() 用于通过“\n”进行初始拆分。

Python3

# Python3 code to demonstrate working of
# Horizontal Concatenation of Multiline Strings
# Using map() + operator.add + join()
from operator import add
  
# initializing strings
test_str1 = '''
geeks 4
geeks'''
test_str2 = '''
is
best'''
  
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
  
# using add to concat, map() to concat each lines zipped
res = '\n'.join(map(add, test_str1.split('\n'), test_str2.split('\n')))
  
# printing result
print("After String Horizontal Concatenation : " + str(res))
输出
The original string 1 is : 
geeks 4
geeks
The original string 2 is : 
is
best
After String Horizontal Concatenation : 
geeks 4is
geeksbest