Reverse a string in Python

前端 未结 28 2488
南旧
南旧 2020-11-21 04:41

There is no built in reverse function for Python\'s str object. What is the best way of implementing this method?

If supplying a very conci

28条回答
  •  抹茶落季
    2020-11-21 05:13

    To solve this in programing way for interview

    def reverse_a_string(string: str) -> str:
        """
        This method is used to reverse a string.
        Args:
            string: a string to reverse
    
        Returns: a reversed string
        """
        if type(string) != str:
            raise TypeError("{0} This not a string, Please provide a string!".format(type(string)))
        string_place_holder = ""
        start = 0
        end = len(string) - 1
        if end >= 1:
            while start <= end:
                string_place_holder = string_place_holder + string[end]
                end -= 1
            return string_place_holder
        else:
            return string
    
    
    a = "hello world"
    rev = reverse_a_string(a)
    print(rev)
    

    Output:

    dlrow olleh
    

提交回复
热议问题