14 - String
14 - String
String
So far we've dealt with numbers and booleans. But there is a very powerful data type
in python, which is the string. String is an immutable ordered data type that stores
sequences of characters. We will discuss later what immutable and ordered mean.
Both of these work the same, and both of them define a string.
String
However, there are some cases where we should use single quotations and some
other cases where we should use double quotations.
String
For example:
Imagine we are trying to write the following:
When using single quotations, this will cause an error, this is invalid in python.
String
There are two solutions to this problem:
As you see, this works fine after replacing ' with ".
String
2. Use a backslash \ before the quotation (aka escape character)
Escape sequences are special characters that allow you to include special characters
in strings.
String Operations
1. Combine (Concatenation)
2. String Repeat
3. len
String Operations
1. Combine (Concatenation)
Hello
World!
We can use the + operator to combine(concatenate) the two strings into one string.
String Operations
1. Combine (Concatenation)
Similar to the + operator with numbers, the + operator with strings allows us to
combine two strings together, to have a new string which is the concatenation of
When using the * operator with strings, we basically repeat the string as much as we
want. In the example below we repeated the string "Hello" 5 times, which resulted in
Notice the difference in the above pictures. Adding an extra space changed the output
We can use the len() function to get the length/size of the string.
Although there are only 10 characters in the string, the output is 11. Why?
This is because the space is between "Omar" and "Marouf" is also considered a
By using the input() keyword, you can allow the user to type on the keyboard and then
This program creates a string variable called name and then assigns the value of this
input to whatever the user enters, and then concatenates "Hello " to the name.
By default, input() is of type string, but we can change (cast) the string into any other