我初学python,想用python写个程序,假如输入abcd,它就输出dcba,哪位大侠知道,望不吝赐教

如题所述

对于序列类型,有些可以用reverse。下面的回答比较让初学者难看懂。因为省略的值会因为最后一个符号而变化。解释见python联机文档。第一个被省略的是len(s),中间被省略的还真不好写,因为如果写0,则由于不包含的缘故,会漏掉s的第一个元素,如果写-1,会被当成len(s),由于python内部实现上是根据最后一个符号先判断的,所以中间省略最好。因为你在python代码写-1被当作end,但是python内部可以使用-1表示开始的。

There are six sequence types: strings, Unicode strings, lists, tuples, buffers, and xrange objects.

s[i:j:k] slice of s from i to j with step k

If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.
The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that . In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become ``end'' values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.

int
PySlice_GetIndicesEx(PyObject *_r, Py_ssize_t length,
Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step,
Py_ssize_t *slicelength)
{
PySliceObject *r = (PySliceObject*)_r;
/* this is harder to get right than you might think */

Py_ssize_t defstart, defstop;

if (r->step == Py_None) {
*step = 1;
}
else {
if (!_PyEval_SliceIndex(r->step, step)) return -1;
if (*step == 0) {
PyErr_SetString(PyExc_ValueError,
"slice step cannot be zero");
return -1;
}
/* Here *step might be -PY_SSIZE_T_MAX-1; in this case we replace it
* with -PY_SSIZE_T_MAX. This doesn't affect the semantics, and it
* guards against later undefined behaviour resulting from code that
* does "step = -step" as part of a slice reversal.
*/
if (*step < -PY_SSIZE_T_MAX)
*step = -PY_SSIZE_T_MAX;
}

defstart = *step < 0 ? length-1 : 0;
defstop = *step < 0 ? -1 : length;

if (r->start == Py_None) {
*start = defstart;
}
else {
if (!_PyEval_SliceIndex(r->start, start)) return -1;
if (*start < 0) *start += length;
if (*start < 0) *start = (*step < 0) ? -1 : 0;
if (*start >= length)
*start = (*step < 0) ? length - 1 : length;
}

if (r->stop == Py_None) {
*stop = defstop;
}
else {
if (!_PyEval_SliceIndex(r->stop, stop)) return -1;
if (*stop < 0) *stop += length;
if (*stop < 0) *stop = (*step < 0) ? -1 : 0;
if (*stop >= length)
*stop = (*step < 0) ? length - 1 : length;
}

if ((*step < 0 && *stop >= *start)
|| (*step > 0 && *start >= *stop)) {
*slicelength = 0;
}
else if (*step < 0) {
*slicelength = (*stop-*start+1)/(*step)+1;
}
else {
*slicelength = (*stop-*start-1)/(*step)+1;
}

return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-10-21
#!/usr/bin/python2.7
str0='abcd'
tmp0=[]
for i in str0:
tmp0.append(i)
tmp0.reverse()
print ''.join(tmp0)
第2个回答  2011-10-21
list = 'abcd'
#这个输出就是’dcba‘
list[::-1]本回答被提问者采纳
相似回答