String functions

K

Kali K E

Hi,

I want two simple things.

1. To find the length of the string
2. To find the contants of the last character in a string. I tried to
use $ for that, but I am getting syntax error. I do not know the
correct format. Basically I have to check
if mystring[lastchr] == '.':
dosomething
else:
donothing

Please help me.
 
C

Chris Tavares

Kali K E said:
Hi,

I want two simple things.

1. To find the length of the string

Use the len function:
2. To find the contants of the last character in a string. I tried to
use $ for that, but I am getting syntax error. I do not know the
correct format. Basically I have to check
if mystring[lastchr] == '.':
dosomething
else:
donothing

Please help me.

Use the indexer. Python sequences (lists, tuples, strings) can take negative
numbers as indexes. If you use a negative number, it starts counting from
the end of the sequence. So, to get the last character, do:

-Chris
 
S

Scott David Daniels

Jordan said:
... Basically I have to check
if mystring[lastchr] == '.':
dosomething
else:
donothing
if str[-1] == '.':
dosomething
else:
donothing

The idiom you want is probably:
if somestr.endswith('.'):
dosomething
else:
donothing

(1) don't use str as a variable name, you'll mask the builtin str.
(2) the above code raises no exception if somestr is length 0.
''[-1] raises an exception, but ''.endswith('whatever') is False.

-Scott David Daniels
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,139
Latest member
JamaalCald
Top