Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a character to the end of every string in a list? [duplicate]

Let's say I have a list:

list = ["word", "word2", "word3"]

and I want to change this list to:

list = ["word:", "word2:", "word3:"]

is there a quick way to do this?

like image 778
hacktheplanet Avatar asked Nov 23 '14 19:11

hacktheplanet


People also ask

How do you add a character to the end of a string?

Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.

How do you add a character after every character in a string?

To insert a character after every N characters, call the replace() method on the string, passing it the following regular expression - str. replace(/. {2}/g, '$&c') . The replace method will replace every 2 characters with the characters plus the provided replacement.

How do you add a value to a string in a list?

Method #2: Using append() This particular function can be used to perform the operation of appending a string element to the end of a list without changing the state of the string to a list of characters.


1 Answers

List comprehensions to the rescue!

list = [item + ':' for item in list]

In a list of

['word1', 'word2', 'word3'] 

This will result in

['word1:', 'word2:', 'word3:']

You can read more about them here.

https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

like image 82
ollien Avatar answered Nov 14 '22 21:11

ollien