如何从python中的列表中删除引号?

时间:2018-08-21 23:17:23

标签: python string list

我在代码中喜欢这个数组:

 displayTodos: function () {
  var todosUl = document.querySelector('ul');
  todosUl.innerHTML = '';
  todoList.todos.forEach(function (todo, position) {
   var todoLi = document.createElement('li');
   todoLi.id = position;
   todoLi.appendChild(this.createSaveButton());
   todosUl.appendChild(todoLi);
  }, this);
 },

createSaveButton: function () {
 var saveButton = document.createElement('button');
 saveButton.textContent = 'Save';
 saveButton.className = 'save-button';
 return saveButton;
},

setUpEventListeners: function () {
 var todosUl = document.querySelector('ul');
 todosUl.addEventListener('click', function (event) {
  var elementClicked = event.target;
  if (elementClicked.className === 'save-button') {
   handlers.changeTodo(parseInt(elementClicked.parentNode.id));
}


<ul>
</ul>
<button id="save-change-button" class="save-change-button">Save</button>

我希望输出将是这样

x = ['"google"','"facebook"',"youtube"]

该怎么做?

1 个答案:

答案 0 :(得分:5)

使用str.strip和列表理解

In [1062]: x = ['"google"','"facebook"',"youtube"]

In [1063]: [i.strip('"') for i in x]
Out[1063]: ['google', 'facebook', 'youtube']

或者,您可以使用map代替列表理解

In [1065]: list(map(lambda i: i.strip('"'), x))
Out[1065]: ['google', 'facebook', 'youtube']

您也可以使用str.replace

In [1074]: [i.replace('"', '') for i in x]
Out[1074]: ['google', 'facebook', 'youtube']

将这三者进行比较,用str.strip进行列表理解是最快的

In [1066]: %timeit([i.strip('"') for i in x])
The slowest run took 12.16 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 805 ns per loop

In [1067]: %timeit(list(map(lambda i: i.strip('"'), x)))
1000000 loops, best of 3: 1.52 µs per loop

In [1075]: %timeit([i.replace('"', '') for i in x])
The slowest run took 5.48 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 975 ns per loop