首先,我知道-=操作在str
中不起作用。
但是有功能相同吗?
我需要这个的原因是因为
def function(self, str_source):
str_source = str_source[:-1] # removing last character of the string
str_source += self.other_function() # adding other characters
return True
在这种功能中,当我执行s = s[:-1]
时,原始字符串不会更改。
我知道为什么它不会改变,我知道我可以返回另一个修改过的字符串,但是我目前正在处理别人的代码,而我无法完成该项目的开发。
那么可以删除函数中字符串的子字符串吗?
答案 0 :(得分:1)
答案 1 :(得分:0)
这是黑客:
import sys
def function(str_source):
# get existing value
gvars = sys._getframe(1).f_globals
lvars = sys._getframe(1).f_locals
if str_source in lvars:
dir = lvars
elif sttr_source in gvars:
dir = gvars
else:
# might want to raise an exception here
print(str_source, "not found")
return False
ext_str = str(dir[str_source])
ext_str = ext_str[:-1] # removing last character of the string
# Store
dir[str_source] = ext_str
return True
s1 = "hello"
function("s1")
s2 = "world"
function("s2")
print(s1)
print(s2)
礼物:
hell
worl