如何在python中向右移动字符串?
我试着把绳子移到右边如何在python中向右移动字符串?,python,Python,我试着把绳子移到右边 最后一个值应为第一个值,其余值紧随其后 s=“I Me You”应该返回“You I Me” 我尝试了以下代码,但无效。请帮助我 sr= "I Me You" def shift_right(sr): L=sr.split() new_list=L[-1] new_list= new_list.append(1,L[:0]) return (new_list) print(shift_right(sr) print (shift_re
- 最后一个值应为第一个值,其余值紧随其后
应该返回s=“I Me You”
“You I Me”
sr= "I Me You"
def shift_right(sr):
L=sr.split()
new_list=L[-1]
new_list= new_list.append(1,L[:0])
return (new_list)
print(shift_right(sr)
print (shift_reverse(sr))
此代码将适用于您
def shift_str(s):
arr = s.split()
first = arr.pop(0)
arr.append(first)
return " ".join(arr)
例如:
shift\u str(“xxx ccc lklklk”)
>>'ccc lklklk xxx'
您可以使用索引和切片创建一个新列表,然后通过空格连接:
print(' '.join([s.split()[-1]] + s.split()[:-1])) # You I Me
首先,我们拆分字符串:
>>> s = "I Me You"
>>> l = s.split()
>>> l
['I', 'Me', 'You']
然后我们添加从最后一个元素到最后一个元素的列表l[-1:]
,以及从开始到最后一个元素(但不包含)的列表l[:-1]
:
>>> l[-1:] + l[:-1]
['You', 'I', 'Me']
最后,我们加入:
>>> ' '.join(l[-1:] + l[:-1])
'You I Me'
使用、字符串切片和字符串连接更快的解决方案:
>>> s = 'I Me You'
>>> lsi = s.rfind(' ')
>>> s[lsi+1:] + ' ' + s[:lsi]
'You I Me'
另一个快速解决方案包括:
在函数形式中:
def find_and_slice(s):
lsi = s.rfind(' ')
return s[lsi+1:] + ' ' + s[:lsi]
def rs(s):
rs = s.rsplit(maxsplit=1)
return rs[1] + ' ' + rs[0]
如果将字符串设为a,则可以使用以下方法:
如果所有分隔符都相同(
split
withoutparameters接受所有空白字符),则可以不使用列表来执行此操作。使用字符串方法,如rindex
或rpartition
:
>>> part = s.rpartition(' ')
>>> part[-1] + part[1] + part[0]
'You I Me'
我的两分钱:
string = 'this is a test string'
new_str = string.split() #The .split() method splits a string into a list
new_str[0],new_str[-1] = new_str[-1], new_str[0] #this is where python gets so amazing
print ' '.join(new_str) #just join the list again
输出
'string is a test this'
现在
比赛时间
也许更有趣的是什么是更快的方法
第一个测试由OP测试字符串(仅3个块)进行,第二个测试由600个单字符块组成的字符串进行
from collections import deque
import timeit
def trivial(s):
l = s.split()
return ' '.join(l[-1:] + l[:-1])
def more_split(s):
return ' '.join([s.split()[-1]] + s.split()[:-1])
def dq(s):
s_deq = deque(s.split())
s_deq.rotate(1)
return ' '.join(s_deq)
def find_and_slice(s):
lsi = s.rfind(' ')
return s[lsi+1:] + ' ' + s[:lsi]
def rs_lazy(s):
return ' '.join(reversed(s.rsplit(maxsplit=1)))
def rs_smart(s):
rs = s.rsplit(maxsplit=1)
return rs[1] + ' ' + rs[0]
def rpart(s):
part = s.rpartition(' ')
return part[-1] + part[1] + part[0]
def time_a_method(m, s):
c_arg = "('{}')".format(s)
t = timeit.timeit(m + c_arg, setup="from __main__ import " + m , number=100000)
print( m + " "*(15-len(m)) + "----> {}".format(t))
if __name__ == '__main__':
print(trivial("I Me You"))
print(more_split("I Me You"))
print(dq("I Me You"))
print(find_and_slice("I Me You"))
print(rs_lazy("I Me You"))
print(rs_smart("I Me You"))
print(rpart("I Me You"))
print("######## USE: 'I Me You'")
for m in ["trivial", "more_split", "dq", "find_and_slice", "rs_lazy", "rs_smart", "rpart"]:
time_a_method(m, "I Me You")
print("######## USE: 'a b c d e f '*100")
s = 'a b c d e f '*100
for m in ["trivial", "more_split", "dq", "find_and_slice", "rs_lazy", "rs_smart", "rpart"]:
time_a_method(m, s)
结果如下:
获胜者是
这让我很惊讶(我赌找到并切分我输了)。课堂上有两个答案:
蛮力:拆分所有字符串
注意我们只需要最后一部分
即使在最简单的情况下,第一种方法也比最佳方法慢2到3倍。显然,当字符串变得更有趣时,第一种方法就变得非常低效
真正有趣的是,投票率最高的答案是速度较慢的:)您的第一个问题是print(shift_right(sr)行中缺少括号
。你的第二个问题是,append
修改一个列表一个列表到位,你不需要new\u list=
。这不是预期的输出。@MalikBrahimi谢谢通知,我已经修复了它以提供正确的输出。OP要求正确的移位而不是leftNice基准是错误的!这告诉我应该更多地使用rpartition。似乎rpartition创建了一个额外的元组对象,这是有成本的,但成本明显低于在Python中执行两个显式切片的成本。我已将rsplit解决方案更新为我认为比使用join和REVERSE更快的解决方案。它更类似于rfind和partition答案。@Shashank更新…bu它不会改变最终结果。是的,我知道,我自己已经运行过了,rpartition和rfind显然仍然是最快的,但我认为,通过避免使用反向和联接,可以使速度提高1.5倍,这仍然很有趣。
>>> part = s.rpartition(' ')
>>> part[-1] + part[1] + part[0]
'You I Me'
string = 'this is a test string'
new_str = string.split() #The .split() method splits a string into a list
new_str[0],new_str[-1] = new_str[-1], new_str[0] #this is where python gets so amazing
print ' '.join(new_str) #just join the list again
'string is a test this'
from collections import deque
import timeit
def trivial(s):
l = s.split()
return ' '.join(l[-1:] + l[:-1])
def more_split(s):
return ' '.join([s.split()[-1]] + s.split()[:-1])
def dq(s):
s_deq = deque(s.split())
s_deq.rotate(1)
return ' '.join(s_deq)
def find_and_slice(s):
lsi = s.rfind(' ')
return s[lsi+1:] + ' ' + s[:lsi]
def rs_lazy(s):
return ' '.join(reversed(s.rsplit(maxsplit=1)))
def rs_smart(s):
rs = s.rsplit(maxsplit=1)
return rs[1] + ' ' + rs[0]
def rpart(s):
part = s.rpartition(' ')
return part[-1] + part[1] + part[0]
def time_a_method(m, s):
c_arg = "('{}')".format(s)
t = timeit.timeit(m + c_arg, setup="from __main__ import " + m , number=100000)
print( m + " "*(15-len(m)) + "----> {}".format(t))
if __name__ == '__main__':
print(trivial("I Me You"))
print(more_split("I Me You"))
print(dq("I Me You"))
print(find_and_slice("I Me You"))
print(rs_lazy("I Me You"))
print(rs_smart("I Me You"))
print(rpart("I Me You"))
print("######## USE: 'I Me You'")
for m in ["trivial", "more_split", "dq", "find_and_slice", "rs_lazy", "rs_smart", "rpart"]:
time_a_method(m, "I Me You")
print("######## USE: 'a b c d e f '*100")
s = 'a b c d e f '*100
for m in ["trivial", "more_split", "dq", "find_and_slice", "rs_lazy", "rs_smart", "rpart"]:
time_a_method(m, s)
You I Me
You I Me
You I Me
You I Me
You I Me
You I Me
You I Me
######## USE: 'I Me You'
trivial ----> 0.1339518820000194
more_split ----> 0.1532761280000159
dq ----> 0.182199565000019
find_and_slice ----> 0.07563322400005745
rs_lazy ----> 0.23457759100006115
rs_smart ----> 0.1615759960000105
rpart ----> 0.06102836100001241
######## USE: 'a b c d e f '*100
trivial ----> 3.2239098259999537
more_split ----> 4.6946649449999995
dq ----> 3.991058845999987
find_and_slice ----> 0.15106809200005955
rs_lazy ----> 0.32278001499992115
rs_smart ----> 0.22939544400003342
rpart ----> 0.10590313199998036
def rpart(s):
part = s.rpartition(' ')
return part[-1] + part[1] + part[0]