How can I access and modify an element in a list if the element is a sentence?

Viewed 29

Suppose I have the following list in python

List= ['Car XXX_2010 Type', 'Length: 14.7', 'Width: 5.8', 'Height: 5.6']

How can I remove the word 'Type' from the first element in the list, while keeping the remaining parts of the element?

In other words, how can I arrive to an output like this:

List= ['Car XXX_2010', 'Length: 14.7', 'Width: 5.8', 'Height: 5.6']
2 Answers

Lets say you want to remove 'Type' from any of the elements. You iterate over the list and use replace function. Here strip function will remove any trailing or preceding blank spaces if any.

List=[i.replace('Type','').strip() for i in List ]

You could simply use .replace() function like so: List[0] = List[0].replace(" Type", "")

.replace takes in two parameters: the string to be replaced, and the string to replace it with. It then returns a new list with the replacement

You can read more about .replace here

Related