简体   繁体   English

如何更改 Python 列表中每个字符串的第 n 个字符

[英]How to change the nth character of every string in a list in Python

Let's say I have the following list of strings:假设我有以下字符串列表:

list = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03']

I want to change the 11th character of each string, meaning the 2nd '.', to a '-'.我想将每个字符串的第 11 个字符(即第二个“.”)更改为“-”。 I've tried:我试过了:

list = [n[:10] + '-' + n[11:] for n in list]

However this gives me the error:然而,这给了我错误:

TypeError: 'float' object is not subscriptable

The problem is that you have a float somewhere in your list.问题是您的列表中某处有一个浮点数。 You could use a for loop using enumerate and str to solve it:您可以使用 for 循环使用enumeratestr来解决它:

lst = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03']
for index, item in enumerate(lst):
    item = str(item)
    lst[index] = item[0:10] + "-" + item[11:]

Or, as a list comprehension:或者,作为列表理解:

new_lst = [item[0:10] + "-" + item[11:]
           for x in lst
           for item in [str(x)]]

Also, avoid calling your variables like builtin-objects ( list , dict and the like).此外,避免调用您的变量,如内置对象( listdict等)。

I just tried it on Jupyter localhost as, (it's working):我刚刚在 Jupyter localhost 上尝试过,(它正在工作):

1 1

>>> a = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03']
>>> a = [n[:10] + '-' + n[11:] for n in a]
>>> a
['ABC.010120-01', 'ABC.010220-02', 'ABC.010220-03']

Note that list , as str , set and some others are word reserved for python3.请注意, list ,如strset和其他一些是为 python3 保留的字。

What you're doing it's like change the base of an int , for example.例如,您所做的就像更改int的基础。

The issue is that there are nan float values in the list.问题是列表中有 nan float 值。 I found that following this solution linked here worked to remove the nan's from my list as so:我发现按照此处链接的此解决方案可以从我的列表中删除 nan,如下所示:

lst = ['ABC.010120.01', 'ABC.010220.02', 'ABC.010220.03', nan]
lst = [x for x in lst if x == x]

Executing that beforehand allows this line to function without error:预先执行该命令允许此行到 function 没有错误:

lst = [n[:10] + '-' + n[11:] for n in last]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM