i am trying to write a program to reverse words of string at there places.
Example:-
str = "my name is xyz"
will become
"ym eman si zyx"
following is the program:-
str = "my name is atharva"
l = str.split()
print(l)
for var in l:
print(var)
temp_str = list(reversed(var))
print(temp_str)
list = ''.join(temp_str)
print(list)
when i run the error i got the following error:-
['my', 'name', 'is', 'atharva']
my
['y', 'm']
ym
name
Traceback (most recent call last):
File "<string>", line 29, in <module>
TypeError: 'str' object is not callable
Thanks in advanace.
Hope to here from you soon.
CodePudding user response:
In the first iteration of your loop, this line assigns a string to list
:
list = ''.join(temp_str)
On the next iteration you're trying to use list
as the built-in function:
list(reversed(var))
But the built-in can no longer be accessed, since you replaced it with your string.
Don't use existing names like list
(or str
for that matter) for your variables. This destroys your access to their existing functionality
CodePudding user response:
You are running over build in function list
list = ''.join(temp_str)
rename your var:
str = "my name is atharva"
l = str.split()
print(l)
for var in l:
print(var)
temp_str = list(reversed(var))
print(temp_str)
str_list= ''.join(temp_str)
print(str_list)
*Also this is a bad practice running over build in function str
CodePudding user response:
The reason is you are using the list
as variable name and assigning it a str
value which shouldn't be the case. Just rename the variable list
to some other name.
Also you can try out this code which is more optimized without using extra lists and all:
str = "my name is atharva"
l = str.split()
out = []
for var in l:
out.append(var[::-1])
print (' '.join(out))
Output:
ym eman si avrahta
CodePudding user response:
You can change your code to what I have provided below:
txt = "my name is atharva"
reversed_list = []
print(txt)
for var in txt.split():
reversed_list.append(var[::-1]) #This reverses the text
print(' '.join(reversed_list))
The output will be:
my name is atharva
ym eman si avrahta
I have change certain variable names too.