Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Subscribe to see which companies asked this question
class Solution(object):
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
b = list(s)
c = len(s)
print("%d",c)
d = []
j = -1
for i in range(1,c+1):
d.append(s[j])
j = j -1
str_convert = ''.join(d)
return str_convert
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
b = list(s)
c = len(s)
print("%d",c)
d = []
j = -1
for i in range(1,c+1):
d.append(s[j])
j = j -1
str_convert = ''.join(d)
return str_convert
因为python的read和write方法的操作对象都是string。而操作二进制的时候会把string转换成list进行解析,解析后重新写入文件的时候,还得转换成string。
>>> import string
>>> str = 'abcde'
>>> list = list(str)
>>> list
['a', 'b', 'c', 'd', 'e']
>>> str
'abcde'
>>> str_convert = ''.join(list)
>>> str_convert
'abcde'
>>> import string
>>> str = 'abcde'
>>> list = list(str)
>>> list
['a', 'b', 'c', 'd', 'e']
>>> str
'abcde'
>>> str_convert = ''.join(list)
>>> str_convert
'abcde'
class Solution(object):
def reverseString(self, s):
""" :type s: str :rtype: str """
return s[:: -1]
""" :type s: str :rtype: str """
return s[:: -1]
所有数,每5个取一个:
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
甚至什么都不写,只写[:]
就可以原样复制一个list:
>>> L[:]
[0, 1, 2, 3, ..., 99]
tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple:
>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)
字符串'xxx'
也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串:
>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'
s1 =
list(s)
s1.reverse()
return ''.join(s1)
s1.reverse()
return ''.join(s1)