A String is a collection of letters/alphabets. It can be a word or a sentence.
The 'Data Type' for String is 'str'.
When Python finds data inside Double Quotes (" ") of Single Quotes (' '). It creates a String type variable for that value.
Or
And that's all! You have a String in place.
Now, what if, you want a paragraph, separated by lines, to be assigned to a variable.
i.e. Let's say, you want to assign the below paragraph to a variable.
In such cases, you can use the three double quotes(""" """) or three singe quotes(''' ''').
Declaring a multiline String with three Double Quotes (""" """) :
x = """In a huge pond, there lived many fish. They were arrogant And never listened to anyone.""" print(x)
Declaring a multiline String with three Single Quotes (''' ''') :
x = '''In a huge pond, there lived many fish. They were arrogant And never listened to anyone.''' print(x)
Now, if you want to access a particular character of a String, how can you do that?
Say, you have a String "Hello". And you want the letter 'e' to be assigned to a variable.
Let us see below.
x = "Hello" y = x[1] print(y)
So, we have a string 'Hello',
And we have assigned 'Hello' to a variable 'x'.
Let us elaborate more, on how the String 'Hello' is stored in the variable 'x'.
So, just for the sake of understanding, you can assume the variable 'x' is divided into '5' parts to store 'Hello'.
Now, if you check from the front, the count starts from '0' and ends with '4'.
Similarly, if you look from the reverse direction, the count starts from '-1' and ends with '-5'.
So, if we look at the next line in the code,
We are trying to access the 2nd location,
So, 'x[1]' is referring to the 2nd location where 'e' is stored.
And we have assigned 'e' to the variable 'y'.
Now, if you look at the print statement,
The value of 'y' is printed as output.
Also, remember that x[1] and x[-4] is referring to the same location that has 'e'. You can use the negative positions or positive. That is completely upto you.
x = "Hello" y = x[-4] print(y)
Next, let us see, how can we access a portion of a String. i.e. Say you want to take 'ell' from the String 'Hello' and store it in a different variable.
x = "Hello" y = x[1:4] print(y)
So, we want to take the chunk of letters/characters from the String 'Hello' and store it into the variable 'y'.
And in the first line, we have stored 'Hello' inside 'x'.
Also, let us see the elaborated structure.
So, we want to take the chunk 'ell' from 'Hello'. And that happens in the next line.
Just note, the position of 'e' from 'ell' is '1' and the position of the last 'l' from 'ell' is 3.
So, the statement, x[1,4] picks the value from position '1' till the position of the 'l' plus 1. i.e. The position of second 'l' is 3. We just add 1 to it.
So, the statement 'x[1:4]' simply refers, "Pick the chunk from position 1 to position (4-1)".
And 'ell' is assigned to the variable 'y'.
And in the next line, we have the print statement,
That prints the chunk of letters 'ell'.
Let us rewrite the above code using the negative positions.
x = "Hello" y = x[-4:-1] print(y)
Next, let us say, we want to update a portion of a String.
Say we have a String "Hello" and we want to update it to "Hellboy".
x = "Hello" y = x[:4] + 'boy' print(y)
So, we have initialised the variable 'x' with the String 'Hello'.
Also, let us see the elaborated structure.
So, we have to replace the letter 'o' with 'boy'.
And as we can see, 'o' is in position '4'. So, we have used the statement,
Where the value of position '4' gets replaced with 'b' followed 'o' and 'y'.
And finally print the value of 'y'.
In the above example, we have seen the '+' sign. And as we know, '+' is used for addition of two numbers.
Well! In Python, '+' can be used to join two Strings as well.
Say, we have two Strings, 'Hello' and 'World'. And we want to join/concatenate them into one String, 'HelloWorld'.
Let us solve it with the below example.
x = "Hello" y = "World" z = x + y print(z)
So, we have stored the String 'Hello' in 'x'.
And, stored the String 'World' in 'y'.
And used the '+' operator to join/concatenate 'Hello' and 'World'.
And store the concatenated value in 'z'.
So, '+' is not just used to add two numbers but '+' is also used to join/concatenate two Strings.
But we cannot use the '+' operator to join/concatenate a number and a String.
i.e. The below code will result into an error.
x = 5 y = "World" z = x + y print(z)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
And as said it ended up with an error.
Just like the '+' operator, Python also provides '*' operator that is used for multiplication.
Well! Even for Strings, '*' operator is somewhat like multiplication.
Just like the '*' operator is used to multiply two numbers. Same logic applies for String as well.
Let us see the below example.
x = "Hello"*3 print(x)
So, if you see the output. The statement,
Repeats the String 'Hello' three times.
Next, let us see how to Iterate through the values of a String.
x = "Hello" for y in x: print(y)
So, each Iteration of 'for loop',
The values are taken from the variable 'x', one by one and put in the variable 'y'.
And values are printed at each Iteration.
Now, let us look at a scenario, where you need to find out, if a particular letter or a chunk of letters is present in the string or not.
Let us check, if the substring 'el' is present in the String 'Hello' or not.
x = "Hello" if "el" in x: print("The sub-string, el is present in the String, Hello") else: print("The sub-string, el is not present in the String, Hello")
So, to check if the substring 'el' is present in the String 'Hello', we have used the 'if' statement.
And the 'if' statement is combined with 'in' keyword to check if the substring 'el' is present in the String 'Hello' or not.
Similarly, there is a keyword 'not in' that checks if the substring is not present.
x = "Hello" if "el" not in x: print("The sub-string, el is present in the String, Hello") else: print("The sub-string, el is not present in the String, Hello")
Now, if you look at the output, although the substring 'el' is present in 'Hello', the output is printed from the 'else' block.
Say, you have stored a number in a variable and you want to insert it in the middle of a String.
i.e. Say, you have two numbers '3' and '4' and you have added them and want to display the result in the following way,
Well! We can achieve it using String formatting.
Let us see, how can we resolve it using 'format( )' method.
x = 3 y = 4 z = x + y result = "The added value of { } and { } is { }" print(result.format(x, y, z))
So, what we have done is, taken the numbers '3' and '4' in two variables, 'x' and 'y'.
And stored the added value in a variable named 'z'.
Now, comes the main part, where we have declared a variable named 'result'. And assigned the String 'The added value of { } and { } is { }' to it.
The braces '{ }' in the above text are placeholders, that will be displaying some values as mentioned in the 'format( )' method.
And in the next line we see the 'format( )' method with the print statement.
So, the String variable 'result' calls the 'format()' method. And what the 'format()' method does is, based on the order it fills the braces '{}' with values.
Also you can specify the order, based on what the values will be placed.
x = 3 y = 4 z = x + y result = "The added value of {1} and {0} is {2}" print(result.format(x, y, z))
Now, if you see the above output, we have changed the order in the format method and we got the new output.
Also, we can change the order using keyword.
x = 3 y = 4 z = x + y result = "The added value of {p} and {q} is {r}" print(result.format(p=x, q=y, r=z))
Now, what we have done is, given temporary names for variables 'x' - p, 'y' - q and 'z' - r in the 'format( )' method.
And they got formatted accordingly.
Strings can also be formatted using the String Formatting Operator i.e. '%'.
Let us rewrite the above example using the String Formatting Operator '%'.
x = 3 y = 4 z = x + y print("The added value of %d and %d is %d" % (x, y, z))
So, inside the 'print(...)' statement, there are two parts.
The left part has the actual String to be printed, with two, so called placeholders %s and %d.
And the right side has the values to be placed in the above placeholder.
Now, if you look at the output,
You can see that '%d' is replaced with the actual values of the variables.
You can see that '%d' is replaced with the actual values of the variables.
Below is the List :
Type | Description |
---|---|
d, i, u | Decimal Number |
x, X | Hexadecimal Number |
o | Octal Number |
f, F | Floating Point Number |
e, E | Exponential Number |
g, G | Floating point/Exponential |
c | Single character |
s, r, a | String |
Next, let us look at the Methods provided by Python to handle Strings more effectively.
x = "Hello" print("The length of the String is ",len(x))