Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to write a program that will simply reverse a string. I get an error that something is not subscriptable or something. Could you guys help me pinpoint why this isn't working?
listreverse(list1):
rlist = []
i = len(list1) - 1
while i >= 0:
rlist.append(list[i])
i = i - 1
return rlist
rlist.append(list[i])
Should be
rlist.append(list1[i])
Right now you're trying to get the index i of the list function.
As #gnibbler points out, you should try to pick variable names that are descriptive and distinct enough that you aren't likely to make a typo like this or confuse one variable for another.
your code can be simplified to:
def string_reverse(string1):
return string1[::-1]
print string_reverse('hello')
it returns:
olleh
Note that your code, when takes a string, returns a list, not a string.
Here if you send a string you get the reversed string and if you send a list you get the reversed list
print string_reverse([1,2,3,4])
returns
[4, 3, 2, 1]
Change
rlist.append(list[i])
To
rlist.append(list1[i])
That will solve your problem..
There are lots of (other) ways to do that in Python:
>>> s = 'Hello World!'
# 1
>>> ''.join(reversed(s))
'!dlroW olleH'
# 2
>>> s[::-1]
'!dlroW olleH'
# 3
>>> r = ''
>>> for i in s:
r = i+r
>>> r
'!dlroW olleH'
# 4
>>> ''.join(list(s)[::-1])
'!dlroW olleH'
you can use this
str='qwerty'
print str[::-1] # it will reverse
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I have defined a fairly simple function that is having an unexpected output. I'm using Steam game reviews and want to use a function to narrow the scope based on game title. This works fine:
one_game = games[games['title'] == "Robocraft"]
The output is a dataframe just like the original. However, when I try to make a function (by passing the same game name as an argument) to slice the dataframe as follows:
def slice(game):
out = games[games['title'] == game],
return(out)
I get a tuple that is "[362 rows x 5 columns],)" instead of a dataframe. Is that because of the return command or is that just something that happens when you use a user defined function?
This seems like all I would need to do is convert the tuple back to a dataframe. However, I can't even do that! When I do, I get this error:
"ValueError: Must pass 2-d input. shape=(1, 362, 5)"
How can I get a dataframe as my output?
Thank you!
The comma at the end of the first line of your function is the problem. It wraps the preceding value in a tuple, see:
>>> 1
1
>>> 1,
(1,)
>>> a = 1
>>> type(a)
1
>>>> a = 1,
>>> type(a)
tuple
So just remove that comma, (and the parentheses after return, because return is a keyword, not a function):
def slice(game):
out = games[games['title'] == game]
return out
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to delete character by character from a string (each time a single character to see what the string is going to look like)
var = 'string'
var1 = ''
cor = []
for i in range(0, len(var)):
varl = var[:i] + var[(i+1):]
cor.append(varl)
print (cor)
This is what am getting
['t', 'sr', 'sti', 'strn', 'strig', 'tring', 'sring', 'sting', 'strng', 'strig', 'strin']
I don't know why am getting the first 5 elements in the list, they should not exist.
Does anyone know how to fix this, Thanks.
There isn't really any reason for this not to work. However, using list comprehension instead, seeing as it solved your problem:
var = 'string'
cor = [var[:i] + var[i+1:] for i in range(len(var))]
print (cor)
Returns
['tring', 'sring', 'sting', 'strng', 'strig', 'strin']
The main reason your output seems strange is the loop which should add len(var) variables max.
for i in range(0, len(var)):
In your variable definitions, you have the second variable defined as var1 (i.e. var'one'), and in your for loop, you have varl (i.e. var'el').
Change varls in your loop to var1 and you'll have what you expect.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to express the result of "funct" as a string but nothing I've tried is working.
def funct(y):
rad = [2+y]
return rad
z = 1;
a = funct(z);
print a
print str(a)
b = str(a);
print b
c = repr(a);
print c
Here's my output:
[3]
[3]
[3]
[3]
What am I missing? Thanks!
Edit: I meant that I'm trying to print it as a string without the brackets. Forgot to include that.
You probably don't want rad to be a list.
Try using () instead of []:
rad = (2+y)
Your function would work like so:
def funct(y):
rad = (2 + y)
return rad
z = 1;
a = funct(z);
print a
#=> "3"
Based on the title of your question, you don't want to change funct itself and you don't want to convert the output of funct into a string. If you want to change a number into a string you need to change the values inside the list output by funct. The problem is that you're turning the repr of the list itself into a string, but not casting the value in the list:
>>> repr([5])
'[5]'
>>> repr(["5"])
"['5']"
You actually want to cast the value in the list:
>>> repr(list(map(str, [5]))) # say `funct(3)` for example
"['5']"
>>> repr(list(str(i) for i in [5]))
"['5']"
Now, if you really just want to turn the output of funct into a string, you're already doing that. Python's just not printing quotes around the string representation of a list because it's printing it.
>>> repr([5]); print([5])
'[5]'
[5]
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
My concept is this, but it can't be execute by my terminal.
raw = ['a','1']
for i in raw:
if i.isdigit() == True:
raw.append(('number',int(i)))
else:
pass
print raw
The error type tells me 'tuple' object has no attribute ‘isdigit'。 What's the other way to detect a 'number string' and convert it into authentic number?
The syntax error is your parentheses on the raw.append line. Additionally, you'll get some odd behavior with appending to the list your iterating over. You could rebuild your list in a comprehension to avoid those:
raw = ['a','1']
raw = [('number', int(i)) if i.isdigit() else i for i in raw]
print raw
Outputs:
['a', ('number', 1)]
The comprehension can be written longhand, but you'd need to change your variable names:
raw = ['a', '1']
new_raw = []
for i in raw:
if i.isdigit(): # no need for the == True here
new_raw.append(('number', int(i)))
else:
new_raw.append(i)
You're getting the syntax error because there's a missing parentheses at the end of raw.append(('number',int(i)). Here's how I would do it:
raw = ['a', '1']
for i, v in enumerate(raw):
try:
raw[i] = int(v)
except ValueError:
pass # non-numeric
You have a syntax error at line 4 where you have an extra parenthesis. Change the following
raw.append(('number',int(i))
to
raw.append('number',int(i))
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
This is the code I am trying to run :
line = "123456789"
p = 2
print line[p,p+2]
And I get the error - TypeError: string indices must be integers, not tuple. How can I use line[ , ] with variables. Any help is appreciated.
You want to use colons for slicing.
line = "123456789"
p = 2
print line[p:p+2]
That works fine.
Output:
34
line = "123456789"
p = 2
print line[p,p+2] # this is incorrect slice notation
the correct form is:
print line[p:p+2] # with a colon
look here for info on strings and string slicing