python - 从列表列表中的字符串中删除字符

标签 python string list replace

我正在尝试格式化一些数据以进行分析。我正在尝试从所有以 one 开头的字符串中删除 '*'。这是数据的一个片段:

[['Version', 'age', 'language', 'Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', 'Q10', 'Q11', 'Q12', 'Q13', 'Q14', 'Q15', 'Q16', 'Q17', 'Q18', 'Q19', 'Q20', 'Q21', 'Q22', 'Q23', 'Q24', 'Q25', 'Q26', 'Q27', 'Q28', 'Q29', 'Q30', 'Q31', 'Q32', 'Q33', 'Q34', 'Q35', 'Q36', 'Q37', 'Q38', 'Q39', 'Q40', 'Q41', 'Q42', 'Q43', 'Q44', 'Q45'], ['1', '18 to 40', 'English', '*distort', '*transfer', '*retain', 'constrict', '*secure', '*excite', '*cancel', '*hinder', '*overstate', 'channel', '*diminish', '*abolish', '*comprehend', '*tolerate', '*conduct', '*destroy', '*foster', 'direct', '*challenge', 'forego', '*cause', '*reduce', 'interrupt', '*enhance', '*misapply', '*exhaust', '*extinguish', '*assimilate', 'believe', 'harmonize', '*demolish', 'affirm', 'trouble', 'discuss', '*force', 'divide', '*remove', '*release', 'highlight', 'reinforce', 'stifle', '*compromise', '*experience', 'evaluate', 'replenish']]

这应该很简单,但我尝试过的都不起作用。例如:

for lst in testList:
    for item in lst:
        item.replace('*', '')

只是给我返回相同的字符串。我还尝试插入一个 if 语句并为字符串中的字符编制索引。我知道我可以访问字符串。例如,如果我说 if item[0] == '*': print item 它会打印正确的项目。

最佳答案

string 是不可变的,因此 item.replace('*','') 返回带有替换字符的字符串,它不会替换它们inplace(它不能,因为 string 是不可变的)。您可以枚举列表,然后将返回的字符串分配回列表 -

例子-

for lst in testList:
    for j, item in enumerate(lst):
        lst[j] = item.replace('*', '')

您也可以通过列表理解轻松地做到这一点 -

testList = [[item.replace('*', '') for item in lst] for lst in testList]

关于python - 从列表列表中的字符串中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31794610/

相关文章:

c# - 错误CS1729 : The type `System.Collections.Generic.List<string>' does not contain a constructor that takes `5' arguments

python - 在 python 中获取 svg 文本大小

python - 找到另一个具有目标路径的文件 - 那个文件在哪里?

string - 如何在Matlab中将字符串变量转换为 boolean 值?

javascript - 列表中的列表后加法和减法按钮将不起作用(JavaScript)

Python - 比较 2 种不同的输出格式 - 逻辑

python - 使用 PyParsing 解析系统日志

python - 在 ConfigParser Python 中使用冒号

c - C 和字符串中的 sizeof 操作

c# - 我应该如何将带有文本后缀的数字转换为 C# 中的整数?