我想要一个像下面这样的程序:
const Api = async() => {
const response = await myApi.get(`/${id}`);
setText(response.data);
setRefreshing(false);
};
我希望输出为“ yx”,但由于程序再次运行相同的字符串,因此输出看起来像“ xx”。
我希望你明白我的意思。
答案 0 :(得分:1)
您可以制作一个转换表,而不是使用str.replace
,它实际上只是一个映射序数值的字典:
>>> string = "hello world"
>>> translation_table = str.maketrans("el", "le")
>>> translation_table
{101: 108, 108: 101}
>>> string.translate(translation_table)
'hleeo wored'
>>>
答案 1 :(得分:0)
您有xy
您用y替换了x,所以您有yy
然后将y替换为x,以便得到xx
您可以这样做:
A="xy"
B=a.replace("x","z")
C=B.replace("y","x")
D=C.replace("z","y")
print(D)
#yx
答案 2 :(得分:0)
我不确定我是否理解您的问题,但这也许可以解决:
a = 'xy'
letters = [char for char in a]
b = ''
for l in reversed(letters):
b += l
print(b)
最终结果是yx
。
答案 3 :(得分:0)
根据您的示例:
c=a.replace("xy","yx")
或者对于更通用的解决方案,如果您不希望在大数据量上获得较高的性能,则可以迭代:
c=[]
for i in range(0,len(a)-1,1):
if a[i]=="x":
c[i] ="y"
elif a[i]=="y" :
c[i] ="x"
else:
c[i] =a[i]