在python的re.sub中替换用户定义的变量

时间:2018-02-13 15:10:30

标签: python-3.x

import re

ip = input("Enter the value : ")
line = "<test></test>"

我尝试了以下方案

re.sub(r'(\<test\>)(\<\/test\>)', r'\1#{ip}\2', line)
re.sub(r'(\<test\>)(\<\/test\>)', r'\1-{ip}\2', line)
re.sub(r'(\<test\>)(\<\/test\>)', r'\1+ip+\2', line)

我想替换像

这样的行
**<test>user_input</test>**

如何在re.sub中使用用户定义的变量

1 个答案:

答案 0 :(得分:0)

创建一个新的字符串,作为re.sub的替换格式:

import re

ip = input('Enter the value: ')
line_to_replace = '<test></test>'
pattern = r'(<test>)(</test>)'

# any one of these could work, but the first will likely be more robust
replacement = r'\1{}\2'.format( ip )
replacement = '\\1{}\\2'.format( ip )
replacement = r'\1' + ip + r'\2';

newReplacedString = re.sub(pattern, replacement, line_to_replace)

或者在提供问题时全部到位:

newReplacedString = re.sub(r'(<test>)(</test>)', r'\1{}\2'.format( ip ), line_to_replace)