I'm trying to reverse a string and using the below code but the resultant reverse list value is None.
The code:
str_a = 'This is stirng' rev_word = str_a.split() rev_word = rev_word.reverse() rev_word = ''.join(rev_word)
It returns the TypeError
. Why?
In Python, there is a built-in function called reverse() that is used to reverse the list. This is a simple and quick way to reverse a list that requires little memory. Syntax- list_name. reverse() Here, list_name means you have to write the name of the list which has to be reversed.
Method 1: Reversing a list using the reversed() and reverse() built-in function. Using the reversed() method and reverse() method, we can reverse the contents of the list object in place i.e., we don't need to create a new list instead we just copy the existing elements to the original list in reverse order.
To reverse a list in Python, you can use negative slicing: As you want to slice the whole list, you can omit the start and stop values altogether. To reverse the slicing, specify a negative step value. As you want to include each value in the reversed list, the step size should be -1.
This is my personal favorite way to reverse a string:
stra="This is a string" revword = stra[::-1] print(revword) #"gnirts a si sihT
or, if you want to reverse the word order:
revword = " ".join(stra.split()[::-1]) print(revword) #"string a is This"
:)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With