Python 反向优先&;第二部分的字符串,并返回他们在一起
如何定义一个函数,将字符串拆分为两个部分,并将其反转?如果字符串为奇数,则保留中间字符(余数) 例如:Python 反向优先&;第二部分的字符串,并返回他们在一起,python,python-3.x,string,slice,Python,Python 3.x,String,Slice,如何定义一个函数,将字符串拆分为两个部分,并将其反转?如果字符串为奇数,则保留中间字符(余数) 例如: revStr(“ “) revStr(“xy“) revStr(“wxyz“) revStr(“vwxyz“) revStr(“uvwxyz“) revStr(“tuvwxyz”) 将输出: xy xwzy wvxzy wvuzyx vutwzyx 我已经试过了,但我甚至不能让偶数字符串正确翻转 def revStr(string): output = " "
revStr(“ “)
revStr(“xy“)
revStr(“wxyz“)
revStr(“vwxyz“)
revStr(“uvwxyz“)
revStr(“tuvwxyz”)
将输出:
xy
xwzy
wvxzy
wvuzyx
vutwzyx
我已经试过了,但我甚至不能让偶数字符串正确翻转
def revStr(string):
output = " "
start = 0
if len (string) % 2 == 0:
x = string[start:start//2]
y = x[::-1]
string = x+y
return(string)
printrevStr("abcdef")
需要一些指导或想法,提前感谢!如果有什么我可以澄清的,请告诉我。导入数学
def revStr(字符串):
一半=长度(字符串)/2
string=string[:math.floor(half):][::-1]+string[math.floor(half):math.ceil(half):]+string[math.ceil(half):][:-1]
返回(字符串)
打印(revStr(“abcde”))
打印(revStr(“abde”))
def rev_str(字符串):
中点=len(字符串)//2
如果len(字符串)%2==0:
返回字符串[0:中点][::-1]+字符串[中点][::-1]
其他:
返回字符串[0:中点][::-1]+字符串[中点]+字符串[中点+1:][:-1]
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
打印(修订号(“”)
印刷品(修订号(“xy”))
打印(版次为“wxyz”)
打印(版次为“vwxyz”)
打印(版次(“uvwxyz”))
打印(版次为“tuvwxyz”)
输出:
xy
xwzy
wvxzy
wvuzyx
vutwzyx
你搞砸的是中间的索引部分,得到了两半。在这里,你可以做的是取一个中间索引值=len//2,然后取一半,这样一半到中间,另一半从中间索引开始。一旦你有了两半,你可以简单地用x[:-1]等将它们反向打印
def revStr(string):
mid=len(string)//2
if len(string)%2 != 0:
x=string[:mid]
middle=string[mid]
y=string[mid+1:]
print(x[::-1],middle,y[::-1],sep='')
else:
x=string[:mid]
y=string[mid:]
print(x[::-1],y[::-1],sep='')
revStr("abcdef")
重新导入
def revStr(关键字):
如果len(关键字)首先使用列表。您的代码中应该包含哪些x
和y
?给他们起个会说话的名字,比如first\u half
,second\u half
,reversed\u first\u half
等等,这样你就可以发现哪里出了问题。另外,a在这里可能会有很大的帮助。;-@das-g绝妙创意
def reverse_string(string):
length = len(string)
mid = length//2
# seperating in 3 parst
first_half, second_half, middle = None, None, None
# seperating string into first half, second half and mid based on length
if length%2==1:
first_half = string[:mid]
second_half = string[mid+1:]
middle = string[mid]
else:
first_half = string[:mid]
second_half = string[mid:]
# reversing the first half and second half
first_half_reverse = first_half[::-1]
second_half_reverse = second_half[::-1]
# assembling the final result together
final_result = None
if middle is not None:
final_result = first_half_reverse + middle + second_half_reverse
else:
final_result = first_half_reverse + second_half_reverse
return final_result