Translate Python to Lua: replace a string character in a list

久未见 提交于 2020-01-16 08:35:34

问题


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.

I want to make this in Lua:

l = ["#01","#02", "#03"]
print(l)

for i in range(len(l)):
    l[i]=l[i].replace("#","")
    #print (i)

print (l)

回答1:


Analog of string.gsub() but without magic characters (plain replacement)

function string:replace(pattern, replace_string, ...)
   return (self:gsub(
      pattern:gsub("%p","%%%0"), 
      replace_string:gsub("%%","%%%%"), 
      ...
   ))
end

Example:

print(string.replace("25%", "%", " percent"))  --> 25 percent
print(("n>=0"):replace(">=", "≥"))             --> n≥0
s = "#01"; print(s:replace("#", ""))           --> 01



回答2:


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]

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


来源:https://stackoverflow.com/questions/45645316/translate-python-to-lua-replace-a-string-character-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!