Strings
Another useful data type is the string. A stringcan contain letters, numbers, and symbols.
name = "Tushar"
age = "16"
breakfast= "Dhokla"
- In the above example, we create a variable
name
and set it to the string value"Tushar"
. - We also set
age
to"16"
andfood
to"Dhokla"
.
Strings need to be within quotes.
Escaping characters
There are some characters that cause problems. For example:
'There's a Dog in my House name Bunny!'
This code breaks because Python thinks the apostrophe in
'There's'
ends the string. We can use the backslash to fix the problem, like this:
'There\'s a Dog in my House named Bunny!'
Access by Index
Each character in a string is assigned a number. This number is called the index. Check out the diagram in the editor.
d = "Dogs"[0]
t = "Tushar"[3]
- In the above example, we create a new variable called d and set it to
"d"
, the character at index zero of the string "dogs"
.
- Next, we create a new variable called t and set it to
"t"
, the character at index three of the string "Tushar"
.
Notice that in the first “cat” example we are calling the 0th letter of “cat” and getting “c” in return. This is because in Python indices begin counting at 0. Therefore, in the string “cats”, the first letter, “c”, is at the 0th index and the last letter, “s”, is at the 3rd index.
No comments: