简体   繁体   中英

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?

You want to replace the middle 3 elements, and use the str.join() method to produce the replacement:

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']

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM