我有这样的代码:
def reverse(text):
l=len(text)
while ((l-1)!=0):
print (str(text[l-1]))
l=l-1
print (str(text[0]))
a=reverse("abc!de@fg")
输出结果如下:
g
f
@
e
d
!
c
b
a
但我想将这些单个字符组合起来,希望输出如下:
gf@ed!cba
我有这样的代码:
def reverse(text):
l=len(text)
while ((l-1)!=0):
print (str(text[l-1]))
l=l-1
print (str(text[0]))
a=reverse("abc!de@fg")
g
f
@
e
d
!
c
b
a
gf@ed!cba
要在每行末尾没有换行符的情况下打印,请执行以下操作:
print('text', end='')
将字符列表合并为一个字符串,可以执行以下操作:
''.join(list_of_characters)
反转字符串的最简单方法:
In [1]: a = "abc!de@fg"
In [2]: print(a[::-1])
gf@ed!cba
print
语句默认会添加一个换行符。不换行打印的简单方法是:sys.stdout.write('some text')
# or
print('some text', end='')
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
print (reverse('abc!de@fg'))
print
会自动换行。def reverse(text):
l = len(text)
aux = ''
while l-1 != 0:
aux += str(text[l-1])
l = l - 1
print (aux)
a = reverse("abc!de@fg")`
附注:尽量避免冗余的括号 =)
def reverse(text):
l=len(text)
output = ""
while ((l-1)!=0):
output += (str(text[l-1]))
l=l-1
output +=(str(text[0]))
print output
a=reverse("abc!de@fg")
希望这能有所帮助
Sequence
的最简单方法是使用切片:>>> string="abc!de@fg"
>>> print(string[::-1])
gf@ed!cba
切片将会给你一个倒序的序列副本。
通常情况下,你希望一个函数只做一件事情。返回一个值和打印一些输出是不同的关注点,因此它们不应该在同一个函数中混淆。如果你有一个返回反转字符串的函数,你可以简单地打印这个函数:
print(reverse("abc"))
然后,你可以看到你的实际算法是好的,虽然不完全符合Pythonic风格:
def reverse(text):
l=len(text)
output = ""
while ((l-1)!=0):
output += (str(text[l-1]))
l=l-1
output +=(str(text[0]))
return output
return text[::-1]
作为您的reverse
函数。 - Cory Kramer