0
Is string[0] right for giving me the first letter of a string?
I am trying to use bracets after my string variable to get first and last letters but it gives "string index out of range" error. Pls help!
10 ответов
0
Your code enters infinite loop, because `run` is always True. To fix that, add the else clause in case of the empty line and move `run=False` there.
I've edited the code of yours in accordance to the review above and added an alternative to compare, cheers!
https://code.sololearn.com/cJHzp84TzUHO/?ref=app
+ 4
Its.Arpy ,
if you are using variable_name[0], it looks like that your string is empty.
if you still have trouble, it could be helpful to see your code.
+ 1
You can use it as a list consisted of a series of single characters.
first letter a[0]
last letter a[-1]
+ 1
Python supports negative indexes, so in order to get the last char of the string one can call string[-1].
The above, however, might throw an exception if the string is empty. To avoid this one can use one-character slices (the len of the slice is 1).
For the beginning of the string: string[:1], will get the element at 0-th position, if any.
For the end of the string: sting[-1:] will get the last element of the string, if any
+ 1
Thanks a lot John!
0
So I just tested my code with Pydroid and it works. What I am doing is the code project in python core for files and so on. I have no idea what is wrong with the Sololearn interpreter.
0
Its.Arpy
Book Titles, right?
Please, share what you've got so far
0
file = open("/usercode/files/books.txt", "r")
l = ""
run = True
while run == True:
l = ""
l = file.readline()
if len(l) > 0:
if l[-1]+l[-2] != "\n":
print(l[0]+str(len(l)-2))
else:
print(l[0]+str(len(l)))
run = False
file.close()
This is all I got for now, atm it just gives no ouput
0
Only one assignment to l is needed (file.readline()), others are useless, since they're overwritten by the last one.
You can check whether the string is an empty one with this `if string` (== `if len(string)`.
"\n" is one character, its len is equal to 1, so you only need to check the last character, and change the len to `len(l)-1`. Also, if `l` were "abc", `l[-1]+l[-2]` would give "cb", not "bc".
0
The ingredients 123