关于字符串操作,我对 Python 还很陌生。 我有一个包含一些对象标签的字段,并且想要在其之前或之后插入文本。 为此,我使用列表中的值来搜索字符串中的特定值。 一旦我这样做了,我就无法操纵所有找到的结果,只能操纵一个值。 我知道字符串在 Python 中的工作方式不同(不可变),但不知道如何以其他方式解决此问题。
objectList = [('Object A','Object B','Object C', 'Object D')]
objectString = '"Object A", "Object B", "Object C", "Object D"'
def transform_toString(objects, old_format):
obj = objects
new_format = old_format
for o in obj:
position = new_format.find(str(o))
new_format = new_format[:position] + ' found' + new_format[position:]
return new_format
transformed_string = transform_toString(objectList, objectString)
这会产生以下输出:
"Object A", "Object B", "Object C", "Object D found"
如何实现以下输出?
“找到对象 A”、“找到对象 B”、“找到对象 C”、“找到对象 D”
最佳答案
您的代码中存在多个错误。
我建议您安装带有调试器的 IDE,以便您可以跳入 forloop 并查看那里发生了什么。
如果您仔细观察,您会发现您正在迭代一个包含 1 个元素的数组,即
('Object A','Object B','Object C', 'Object D ')
(它是一个包含 4 个项目的元组),并且您正在字符串中搜索整个元组。在不同的编程语言中,这通常会导致错误,但是这里它尝试找到整个元组它在末尾写入
found
的原因是,如果您查看返回值(我建议也查看文档),它会返回-1
表示未找到该元素。在Python中,-1
表示数组中的最后一个元素(在本例中是字符串中的最后一个字符)
但是,如果你修正了类型,结果仍然不是你想要的。如果删除 parantases,您将得到“foundObject A”、“foundObject B”、“foundObject C”、“foundObject D”
。为了解决这个问题,您需要将指针(位置
)移动字长的偏移量。
固定代码:
objectList = ['Object A', 'Object B', 'Object C', 'Object D']
objectString = '"Object A", "Object B", "Object C", "Object D"'
def transform_toString(objects, old_format):
obj = objects
new_format = old_format
for o in obj:
position = new_format.find(str(o))
if position == -1:
continue
position += len(o)
new_format = new_format[:position] + ' found' + new_format[position:]
return new_format
transformed_string = transform_toString(objectList, objectString)
print(transformed_string)
# "Object A found", "Object B found", "Object C found", "Object D found"
此外,我建议您首先尝试调试代码,然后提出问题。这似乎是学校交给你的一项简单任务。
关于python - 在for循环中操作字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72476832/