Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Checking a string's first and last character

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.

like image 774
Chuvi Avatar asked Nov 13 '13 13:11

Chuvi


People also ask

How do you find the last and first letter of a string?

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.

How do you check if the first character of a string is a letter Python?

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).

How do you read the last character of a string in Python?

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.

How do I get the last two letters of a string in Python?

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.


1 Answers

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 
like image 64
thefourtheye Avatar answered Sep 18 '22 17:09

thefourtheye