将Python转换为Lua:替换列表中的字符串字符 [英] Translate Python to Lua: replace a string character in a list
本文介绍了将Python转换为Lua:替换列表中的字符串字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习Lua,我对python有一定的了解,我想像在python中一样替换字符串中的字符,但是我并没有幸运地找到确切的翻译功能.
I'm learning Lua and I have some knowledge of python and I want to replace a character in a string just like in python but I didn't get lucky to find the exact translation functions.
我想在Lua中做这个
l = ["#01","#02", "#03"]
print(l)
for i in range(len(l)):
l[i]=l[i].replace("#","")
#print (i)
print (l)
推荐答案
首先在Python中,您将使用列表推导:
Firstly in Python you would use a list comprehension:
>>> l = ["#01", "#02", "#03", "04"]
>>> l = [s.replace('#', '') for s in l]
>>> print(l)
['01', '02', '03', '04']
如果您确实需要更新列表:
If you really need to update the list in place:
>>> l[:] = [s.replace('#', '') for s in l]
在Lua中,您可以使用 for
遍历列表/数组/表使用 gsub
替换子字符串:
In Lua you can iterate over the list/array/table with for
and use gsub
to replace the substrings:
> l = {"#01", "#02", "#03", "04"}
> for k, v in pairs(l) do print(k, v) end
1 #01
2 #02
3 #03
4 04
> for k in next,l do l[k] = l[k]:gsub("#", "") end
> for k, v in pairs(l) do print(k, v) end
1 01
2 02
3 03
4 04
这篇关于将Python转换为Lua:替换列表中的字符串字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文