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

2024-05-02 16:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想删除列表中每个项目的第一个字母,条件是项目的第一个字母是“j”。列表中唯一要更改的项目是以字母“j”开头的项目,其余项目保持不变。你知道吗

所需的输出应如下所示:

x = ["ames", "ohn", "robert", "michael", "william", "david", "richard", "charles", "oseph", "thomas", "christopher"]

我尝试了各种传统的for loops,但没有得到想要的结果。我在访问列表中特定索引处的字符串时遇到问题!你知道吗

这只是一个例子,我的列表包含了上万个条目。你知道吗

谢谢!你知道吗


Tags: 项目字符串richard列表字母thomasjohnrobert
3条回答

您可以使用lstrip,即

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

使用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']

最佳方法是使用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']

希望这能回答你的问题!!!

相关问题 更多 >