使用循环在Python中反转字符串? [英] Reversing a string in Python using a loop?

查看:433
本文介绍了使用循环在Python中反转字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我可以用一个循环来反转一个函数中的随机字符串(for循环或while?)。不使用。join(reversed(string)) string [:: - 1] 方法,所以它是一个有点棘手。



我的代码看起来像这样:

  def reverse(text):
while len(text)> 0:
print text [(len(text)) - 1],
del(text [(len(text)) - 1]

我使用打印在同一行上的每一个字母在文本中!



我在 del(text [(len(text)) - 1]



有什么建议吗?

解决方案

问题是你不能在python的字符串中使用 del
然而这段代码没有del,并且希望能做到这一点:

  def reverse(text):
a =
我在范围内(1,le n(text)+ 1):
a + = text [len(text) - i]
返回一个

print(reverse(Hello World!))#prints :!dlroW olleH


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?).

I can not use ".join(reversed(string)) or string[::-1] methods here so it's a bit tricky.

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]

Any suggestions?

解决方案

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:

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

这篇关于使用循环在Python中反转字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆