[英]Join special characters in list elements
How to join some special characters in a particular element in a list? 如何在列表中的特定元素中加入一些特殊字符?
eg 例如
lst = ['Bhanu','23','08','1989','Hello World']
How to add a special character "/"
in between 23
, 08
, 1989
and make it as '23/08/1989'
as a single element of a list? 如何在
1989
23
08
日之间添加特殊字符"/"
,并将其作为“ '23/08/1989'
作为列表的单个元素?
You want to replace the middle 3 elements, and use the str.join()
method to produce the replacement: 您要替换中间的三个元素,并使用
str.join()
方法生成替换内容:
lst[1:4] = ['/'.join(lst[1:4])]
Note that the right-hand-side expression is put into a list object, so you can replace multiple elements in the original list with just the one result. 请注意,右侧表达式已放入列表对象,因此您可以仅用一个结果替换原始列表中的多个元素。
Demo: 演示:
>>> lst = ['Bhanu','23','08','1989','Hello World']
>>> '/'.join(lst[1:4])
'23/08/1989'
>>> lst[1:4] = ['/'.join(lst[1:4])]
>>> lst
['Bhanu', '23/08/1989', 'Hello World']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.