Finding the length of a string
>>> message = "new string">>> len(message)
10
So to find the length of string x you simply use len(x) . The function len() gets called with x as a parameter and returns the length as a return value. 10 in this case.
Accessing string elements by Index
>>> message = "new string"
>>> print(message[0])
n
>>> print(message[1])
e
>>> print (message[2])
w
All stuff in the string (i.e. couple of letters,numbers, characters strung to each other) can be accessed individually using the [] operator . The first character(letter) is at index 0 or numbered by 0. Hence print(message[0]) gave us the first letter in the string message which is 'n'. Moving to the next index(number) moves us to the next character(letter). This is really simple stuff.
Going through all letters of a string
>>> for letter in message:print(letter)
n
e
w
s
t
r
i
n
g
This is a for loop and goes through all letters in the string message.
Testing if two strings match( are the same)
>>> message = "new string"
>>> m = "new string"
>>> if m == message:
print("They match")
They match
No comments:
Post a Comment