str = 'hello'
newstr = ''
count = -1
for i in range (len(str)):
newstr += str[count]
count = count - 1
print (newstr)
答案 0 :(得分:2)
在Python调试器中执行脚本,如下所示:
$ python -m pdb script.py
并使用(s)和变量名来理解它是如何工作的。
答案 1 :(得分:0)
此程序有效,因为您正在读取从最后一个元素到第一个元素的IF (OBJECT_ID('tempdb..#unpvt') IS NOT NULL) DROP TABLE #unpvt;
SELECT Report, Val, [Date]
INTO #unpvt
FROM
(
SELECT [Date], [Report1], [Report2]
FROM YourTable
) p
UNPIVOT
(Val FOR Report IN ([Report1], [Report2])
)AS unpvt;
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @sql AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ', ' + QUOTENAME([Date])
FROM YourTable c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,2,'');
SET @sql = 'SELECT Report, ' + @cols + ' FROM
(
SELECT * FROM #unpvt
) x
PIVOT
(
MAX(Val)
FOR [Date] in (' + @cols + ')
) p ';
EXECUTE(@sql);
。您的str
变量指向给定元素并降低其值。在Python中,负指数意味着从最后一个元素读取。
答案 2 :(得分:0)
如果你一次吃一口,这很简单。在python中,设置count = -1
意味着你想要获取字符串中的最后一项(可以看作是一个字符数组)。您的for i in range (len(str)):'
表示您根据字符串的长度进行循环。行newstr += str[count]
会将字符串的最后一个字母添加到空字符串中。 (所以,如果这个词是“苹果”,那么它将与'newstr
相加'e'。最后,每次执行循环时,您的count
变量将减少,这将允许您反转字符串。
示例:
myStr = "apple"
count = len(myStr) // length is = 5
myStr[count] // this means that it will access the fifth letter
count = count - 1
myStr[count] // now it is accessing the 4th letter
答案 3 :(得分:0)
stri = 'hello' # Make string stri
newstr = '' # Make string newstr
count = -1 # make int count
for i in range (len(stri)): # setting i to 0,1,2,3,4 -> this is a loop
newstr += stri[count] # Add letter to newstr from last letter to first
count = count - 1 # making count go down
print (newstr) # print "olleh"
不要使用str作为变量名,因为它是一个构建函数