can anyone please explain what is wrong with this code?
str1='"xxx"' print str1 if str1[:1].startswith('"'): if str1[:-1].endswith('"'): print "hi" else: print "condition fails" else: print "bye"
The output I got is:
Condition fails
but I expected it to print hi
instead.
To get the first and last characters of a string, access the string at the first and last indexes. For example, str[0] returns the first character, whereas str[str. length - 1] returns the last character of the string.
Python String isalpha() method is a built-in method used for string handling. The isalpha() methods returns “True” if all characters in the string are alphabets, Otherwise, It returns “False”. This function is used to check if the argument includes only alphabet characters (mentioned below).
The last character of a string has index position -1. So, to get the last character from a string, pass -1 in the square brackets i.e. It returned a copy of the last character in the string. You can use it to check its content or print it etc.
Use slice notation [length-2:] to Get the last two characters of string Python. For it, you have to get the length of string and minus 2 char.
When you say [:-1]
you are stripping the last element. Instead of slicing the string, you can apply startswith
and endswith
on the string object itself like this
if str1.startswith('"') and str1.endswith('"'):
So the whole program becomes like this
>>> str1 = '"xxx"' >>> if str1.startswith('"') and str1.endswith('"'): ... print "hi" >>> else: ... print "condition fails" ... hi
Even simpler, with a conditional expression, like this
>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails") hi
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