Python 中两个字符串元组的连接


当需要连接两个字符串元组时,可以使用 'zip' 方法和生成器表达式。

zip 方法获取可迭代对象,将它们聚合到元组中,并将其作为结果返回。

生成器是创建迭代器的简单方法。它自动实现带 '__iter__()' 和 '__next__()' 方法的类,并跟踪内部状态以及在没有可以返回的值时引发 'StopIteration' 异常。

以下是演示 -

示例

实时演示

my_tuple_1 = ('Jane', 'Pink', 'El')
my_tuple_2 = ('Will', 'Mark', 'Paul')

print ("The first tuple is : " )
print(my_tuple_1)
print ("The second tuple is : " )
print(my_tuple_2)

my_result = tuple(elem_1 + elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))

print("The concatenated tuple is : ")
print(my_result)

输出

The first tuple is :
('Jane', 'Pink', 'El')
The second tuple is :
('Will', 'Mark', 'Paul')
The concatenated tuple is :
('JaneWill', 'PinkMark', 'ElPaul')

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义了两个元组列表(字符串),并在控制台上显示。
  • 迭代这些列表,并使用 'zip' 方法对它们进行压缩处理。
  • 从两个元组列表中添加/连接第一个和第二个元素。
  • 然后将其转换为元组。
  • 此操作分配给变量。
  • 该变量是显示在控制台上的输出。

更新于: 2021 年 3 月 11 日

1 千次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告