以 Python 方式更新字符串中的值
Pythonically updating a value in a string
我的字符串可能包含方括号中的数字。如果他们这样做,我想将最后一组方括号中的数字增加一个。
old_content='Some text\t\t[1.00]\nSome other text'
到目前为止我有代码可以做到这一点,但感觉不像 pythonic。
open_indexes = [i for i, c in enumerate(old_content) if c == "["]
close_indexes = [i for i, c in enumerate(old_content) if c == "]"]
start = old_content[:open_indexes[-1]+1]
end = old_content[close_indexes[-1]:]
num = old_content[open_indexes[-1]+1:close_indexes[-1]]
num = float(num)+1
new_content =start +str(num) + end
是否有更 pythonic 的方式来做到这一点?
使用正则表达式
使用sub
function of the re
模块,你可以传递一个函数作为替换:
import re
old_content = 'Some text\t\t[1.00]\nSome other text[3.00]'
def add_one_to_match(match):
num = float(match[1])
return f"[{num + 1}]"
new_content = re.sub(r'\[([^]]*)\][^[]*$', add_one_to_match, old_content)
print(repr(new_content))
使用字符串函数
您可以双partition
右边的字符串(只取最后一次出现):
old_content = 'Some text\t\t[1.00]\nSome other text[3.00]'
start, _, end = old_content.rpartition('[')
num, _, end = end.rpartition(']')
print(repr(f"{start}[{float(num)+1}]{end}"))
两种方式都会得到:
'Some text\t\t[1.00]\nSome other text[4.0]'
使用 re.findall
将字符串拆分为 3 部分:pre、number、post。将数字加 1,然后将各部分连接回一个字符串。
import re
old_content = 'Some text\t\t[1.00]\nSome other text'
matches = list(re.findall(r"(.*\[)(.*)(\].*)", old_content, re.S)[0])
matches[1] = str(float(matches[1]) + 1)
new_content = "".join(matches)
print(new_content)
# Some text [2.0]
# Some other text
我的字符串可能包含方括号中的数字。如果他们这样做,我想将最后一组方括号中的数字增加一个。
old_content='Some text\t\t[1.00]\nSome other text'
到目前为止我有代码可以做到这一点,但感觉不像 pythonic。
open_indexes = [i for i, c in enumerate(old_content) if c == "["]
close_indexes = [i for i, c in enumerate(old_content) if c == "]"]
start = old_content[:open_indexes[-1]+1]
end = old_content[close_indexes[-1]:]
num = old_content[open_indexes[-1]+1:close_indexes[-1]]
num = float(num)+1
new_content =start +str(num) + end
是否有更 pythonic 的方式来做到这一点?
使用正则表达式
使用sub
function of the re
模块,你可以传递一个函数作为替换:
import re
old_content = 'Some text\t\t[1.00]\nSome other text[3.00]'
def add_one_to_match(match):
num = float(match[1])
return f"[{num + 1}]"
new_content = re.sub(r'\[([^]]*)\][^[]*$', add_one_to_match, old_content)
print(repr(new_content))
使用字符串函数
您可以双partition
右边的字符串(只取最后一次出现):
old_content = 'Some text\t\t[1.00]\nSome other text[3.00]'
start, _, end = old_content.rpartition('[')
num, _, end = end.rpartition(']')
print(repr(f"{start}[{float(num)+1}]{end}"))
两种方式都会得到:
'Some text\t\t[1.00]\nSome other text[4.0]'
使用 re.findall
将字符串拆分为 3 部分:pre、number、post。将数字加 1,然后将各部分连接回一个字符串。
import re
old_content = 'Some text\t\t[1.00]\nSome other text'
matches = list(re.findall(r"(.*\[)(.*)(\].*)", old_content, re.S)[0])
matches[1] = str(float(matches[1]) + 1)
new_content = "".join(matches)
print(new_content)
# Some text [2.0]
# Some other text