修改列表中的字符串-在特定索引处

时间:2019-02-28 07:46:47

标签: python python-3.x

我有一个包含一些字符串的列表:

for (let boxes = document.getElementsByClassName("content-box"), i = 0
    ; i < boxes.length; i++) {

  let $link = "#";
  const box = boxes[i];
  const $id = box.id;

  // same code at `for..of` loop
}

我要删除列表中每个项目的首字母,条件是该项目的首字母为“ j”。列表中唯一要更改的项目是以字母“ j”开头的字母,其余的保持不变。

所需的输出应如下所示:

x = ["james", "john", "robert", "michael", "william", "david", "richard", "charles", "joseph", "thomas", "christopher"]

我尝试了各种传统的x = ["ames", "ohn", "robert", "michael", "william", "david", "richard", "charles", "oseph", "thomas", "christopher"] ,但没有得到理想的结果。我在访问特定索引的列表中的字符串时遇到问题!

这只是一个例子,我的列表包含数万个项目。

谢谢!

4 个答案:

答案 0 :(得分:4)

使用str.startswith检查字符串是否以j开头,然后使用切片将其删除。

例如:

x = ["james", "john", "robert", "michael", "william", "david", "richard", "charles", "joseph", "thomas", "christopher"]
print([i[1:] if i.startswith("j") else i for i in x])

输出:

['ames', 'ohn', 'robert', 'michael', 'william', 'david', 'richard', 'charles', 'oseph', 'thomas', 'christopher']

答案 1 :(得分:1)

您可以使用lstrip,即

[i.lstrip('j') for i in x]
#['ames', 'ohn', 'robert', 'michael', 'william', 'david', 'richard', 'charles', 'oseph', 'thomas', 'christopher']

答案 2 :(得分:1)

最佳方法是使用lstrip

prob =["james", "john", "robert", "michael", "william", "david", "richard", "charles", "joseph", "thomas", "christopher"]
prob = [a_prob.lstrip('j') for a_prob in prob]
print(prob)

输出:

['ames', 'ohn', 'robert', 'michael', 'william', 'david', 'richard', 'charles', 'oseph', 'thomas', 'christopher']

希望这能回答您的问题!

答案 3 :(得分:0)

itemgetter用于从可迭代的索引中获取价值。 请参阅此link

from operator import itemgetter
data = itemgetter(0)
print([val[1:] if data(val) == 'j' else val for val in x])
>>> ['ames', 'ohn', 'robert', 'michael', 'william', 'david', 'richard', 'charles', 'oseph', 'thomas', 'christopher']
相关问题