Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

python - Is there a way to insert a single character string into selected string items in a list?

for example:

list = ['a','b','c','d']

i want to insert the letter 'j' in front of the first two strings

which will make the list like this

list = ['ja','jb','c','d']

I know how to append strings into the list but not strings into the items in a list.

question from:https://stackoverflow.com/questions/65948675/is-there-a-way-to-insert-a-single-character-string-into-selected-string-items-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use list comprehension on a slice and get it done.

list1[0:1] = ['j'+x for x in list1[0:2]]

The output of this will be:

['ja', 'jb', 'c', 'd']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...