[英]How to insert a character before first number in a string?
我有一个Python 3程序,它接受诸如!down3
或!up48
。 我希望在数字和命令的其余部分(例如!upx48
或!downx3
)之间插入一个字符(字母x)。 字母x只能插入该位置。
这些命令只能是“上”,“下”,“左”或“右”,并且数字最多为2位数字(和整数)。
最简单的方法是什么?
您可以遍历命令并插入'x'
:
def insert_x(command):
for i, c in enumerate(command):
if c.isdigit():
break
return command[:i] + 'x' + command[i:]
例子:
>>> insert_x('!down3')
'!downx3'
>>> insert_x('!up48')
'!upx48'
您可以使用正则表达式:
>>> li=["!down3", "!up48"]
>>> [re.sub(r'^(\D)(up|down|left|right)(\d+)',r'\1\2x\3', s) for s in li]
['!downx3', '!upx48']
您还可以选择只匹配完整字符串和只有两位数字(如您所述)的picker:
>>> [re.sub(r'^(\D)(up|down|left|right)(\d{1,2})$',r'\1\2x\3', s) for s in li]
您可以尝试以下方法:
command = "!down3"
indexes = [i for i, a in enumerate(command) if a.isdigit()]
command = list(command)
x = "somevalue"
command.insert(indexes[0], x)
print ''.join(command)
import re
def insertX(s):
split = re.split('(\d.*)',s)
return "x".join(split[:-1])
s = "!down354"
insertX(s)
结果:
!downx354
如果您经常使用这种方法,那么答案可能是:
cmds = {d+str(i):d+'x'+str(i) for i in range(10,100) for d in ['up','down','left','right']}
print cmds
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.