使用循环反转 Python 中的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41322315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reversing a string in Python using a loop?
提问by Daniel B?ck
I'm stuck at an exercise where I need to reverse a random string in a function using only a loop (for loop or while?).
我被困在一个练习中,我需要仅使用循环(for 循环或 while?)反转函数中的随机字符串。
I can not use ".join(reversed(string))
or string[::-1]
methods here so it's a bit tricky.
我不能在这里使用".join(reversed(string))
或string[::-1]
方法,所以有点棘手。
My code looks something like this:
我的代码看起来像这样:
def reverse(text):
while len(text) > 0:
print text[(len(text)) - 1],
del(text[(len(text)) - 1]
I use the ,
to print out every single letter in text on the same line!
我使用 将,
文本中的每个字母打印在同一行!
I get invalid syntax on del(text[(len(text)) - 1]
我得到无效的语法 del(text[(len(text)) - 1]
Any suggestions?
有什么建议?
回答by Psidom
Python string is not mutable, so you can not use the del
statement to remove characters in place. However you can build up a new string while looping through the original one:
Python 字符串是不可变的,因此您不能使用该del
语句在原地删除字符。但是,您可以在循环遍历原始字符串时构建一个新字符串:
def reverse(text):
rev_text = ""
for char in text:
rev_text = char + rev_text
return rev_text
reverse("hello")
# 'olleh'
回答by Mukesh Ingham
The problem is that you can't use del
on a string in python.
However this code works without del and will hopefully do the trick:
问题是你不能del
在 python 中使用字符串。然而,这段代码在没有 del 的情况下工作,希望能做到这一点:
def reverse(text):
a = ""
for i in range(1, len(text) + 1):
a += text[len(text) - i]
return a
print(reverse("Hello World!")) # prints: !dlroW olleH
回答by Teja
Python strings are immutable. You cannot use del on string.
Python 字符串是不可变的。您不能在字符串上使用 del。
text = 'abcde'
length = len(text)
text_rev = ""
while length>0:
text_rev += text[length-1]
length = length-1
print text_rev
Hope this helps.
希望这可以帮助。
回答by Eddie
Here is my attempt using a decorator and a for loop. Put everything in one file.
这是我使用装饰器和 for 循环的尝试。将所有内容放在一个文件中。
Implementation details:
实施细则:
def reverse(func):
def reverse_engine(items):
partial_items = []
for item in items:
partial_items = [item] + partial_items
return func(partial_items)
return reverse_engine
Usage:
用法:
Example 1:
示例 1:
@reverse
def echo_alphabets(word):
return ''.join(word)
echo_alphabets('hello')
# olleh
Example 2:
示例 2:
@reverse
def echo_words(words):
return words
echo_words([':)', '3.6.0', 'Python', 'Hello'])
# ['Hello', 'Python', '3.6.0', ':)']
Example 3:
示例 3:
@reverse
def reverse_and_square(numbers):
return list(
map(lambda number: number ** 2, numbers)
)
reverse_and_square(range(1, 6))
# [25, 16, 9, 4, 1]