Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




PYTHON - STRINGS


A String is a collection of letters/alphabets. It can be a word or a sentence.


The 'Data Type' for String is 'str'.


Declaring a String with Double Quotes (" ") or Single Quotes (' ')


When Python finds data inside Double Quotes (" ") of Single Quotes (' '). It creates a String type variable for that value.


x = "Hello World"

Or


x = 'Hello World'

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 a huge pond,
there lived many fish.
They were arrogant
And never listened to anyone."

In such cases, you can use the three double quotes(""" """) or three singe quotes(''' ''').


Declaring a multiline String with three Double Quotes (""" """) or three Single Quotes (''' ''')


Declaring a multiline String with three Double Quotes (""" """) :


Example :


x = """In a huge pond, 
there lived many fish.
They were arrogant 
And never listened to anyone."""
print(x)

Output :



  In a huge pond,
  there lived many fish.
  They were arrogant
  And never listened to anyone.

Declaring a multiline String with three Single Quotes (''' ''') :


Example :


x = '''In a huge pond, 
there lived many fish.
They were arrogant 
And never listened to anyone.'''
print(x)


Output :



  In a huge pond,
  there lived many fish.
  They were arrogant
  And never listened to anyone.

Note : Just remember, declaring a multiline String with three Double Quotes (""" """) is same as declaring a multiline String with three Single Quotes (''' ''')

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.


Accessing the characters of a String


Example :


x = "Hello"
y = x[1]
print(y)


Output :



  e

So, we have a string 'Hello',


x = "Hello"

And we have assigned 'Hello' to a variable 'x'.


java_Collections

Let us elaborate more, on how the String 'Hello' is stored in the variable 'x'.


java_Collections

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,


y = x[1]

We are trying to access the 2nd location,


java_Collections

So, 'x[1]' is referring to the 2nd location where 'e' is stored.


y = x[1]

And we have assigned 'e' to the variable 'y'.


java_Collections

Note : The square brackets '[]' are used with the string type variable to get the variable at that position(i.e. x[1] refers to the 2nd location that contains 'e').

Now, if you look at the print statement,


print(y)

The value of 'y' is printed as output.


Output :



  e

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.


Example :


x = "Hello"
y = x[-4]
print(y)


Output :



  e

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.


Accessing a chunk of letters/characters from a String


Example :


x = "Hello"
y = x[1:4]
print(y)


Output :



  ell

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'.


x = "Hello"

java_Collections

Also, let us see the elaborated structure.


java_Collections

So, we want to take the chunk 'ell' from 'Hello'. And that happens in the next line.


y = x[1:4]

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)".


Note : The end position of 'x[1:4]' i.e. 4, might look a little weird. Looks like it should be '3' instead of '4'. But that is the way it is.

And 'ell' is assigned to the variable 'y'.


java_Collections

And in the next line, we have the print statement,


print(y)

That prints the chunk of letters 'ell'.


Output :



  ell

Let us rewrite the above code using the negative positions.


Example :


x = "Hello"
y = x[-4:-1]
print(y)


Output :



  ell

Next, let us say, we want to update a portion of a String.


Updating a portion of a String


Say we have a String "Hello" and we want to update it to "Hellboy".


Example :


x = "Hello"
y = x[:4] + 'boy'
print(y)    

Output :



  Hellboy

So, we have initialised the variable 'x' with the String 'Hello'.


x = "Hello"

java_Collections

Also, let us see the elaborated structure.


java_Collections

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,


y = x[:4] + 'boy'

Where the value of position '4' gets replaced with 'b' followed 'o' and 'y'.


java_Collections

And finally print the value of 'y'.


print(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.


Concatenation of Strings


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.


Example :


x = "Hello"
y = "World"
z = x + y
print(z)  

Output :



  HelloWorld

So, we have stored the String 'Hello' in 'x'.


x = "Hello"

And, stored the String 'World' in 'y'.


y = "World"

And used the '+' operator to join/concatenate 'Hello' and 'World'.


z = x + y

And store the concatenated value in 'z'.


java_Collections

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.


Example :


x = 5
y = "World"
z = x + y
print(z)


Output :



  z = x + y

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.


Repetition of a String


Just like the '*' operator is used to multiply two numbers. Same logic applies for String as well.


Let us see the below example.


Example :


x = "Hello"*3
print(x)    


Output :



  HelloHelloHello

So, if you see the output. The statement,


x = "Hello"*3

Repeats the String 'Hello' three times.


Next, let us see how to Iterate through the values of a String.


Iterate through a String


Example :


x = "Hello"
for y in x:
print(y) 


Output :



  H
  e
  l
  l
  o

So, each Iteration of 'for loop',


for y in x:

The values are taken from the variable 'x', one by one and put in the variable 'y'.


And values are printed at each Iteration.


print(y)

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.


Checking if a substring is present in a String or not


Let us check, if the substring 'el' is present in the String 'Hello' or not.


Example :


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")	
     


Output :



  The sub-string, el is present in the String, Hello

So, to check if the substring 'el' is present in the String 'Hello', we have used the 'if' statement.


if "el" in x:

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.


Example :


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")	


Output :



  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.


The sub-string, el is not present in the String, Hello

Note : The below topic 'String Formatting' is already explained in the tutorial 'Input & Output'.

String Formatting


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,


The added result of 3 and 4 is 7

Well! We can achieve it using String formatting.


String formatting using 'format( )' method


Let us see, how can we resolve it using 'format( )' method.


Example :


x = 3
y = 4
z = x + y
result = "The added value of { } and { } is { }"
print(result.format(x, y, z))


Output :



  The added value of 3 and 4 is 7

So, what we have done is, taken the numbers '3' and '4' in two variables, 'x' and 'y'.


x = 3
y = 4

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.


result = "The added value of { } and { } is { }"

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.


print(result.format(x, y, z))

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.


result.format(x, y, z)

java_Collections

Also you can specify the order, based on what the values will be placed.


Example :


x = 3
y = 4
z = x + y
result = "The added value of {1} and {0} is {2}"
print(result.format(x, y, z))


Output :



  The added value of 4 and 3 is 7

Now, if you see the above output, we have changed the order in the format method and we got the new output.


result.format(x, y, z)

java_Collections

Also, we can change the order using keyword.


Example :


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))


Output :



  The added value of 3 and 4 is 7

Now, what we have done is, given temporary names for variables 'x' - p, 'y' - q and 'z' - r in the 'format( )' method.


print(result.format(p=x, q=y, r=z))

And they got formatted accordingly.


result = "The added value of {p} and {q} is {r}"

Strings can also be formatted using the String Formatting Operator i.e. '%'.


String Formatting Operator '%'


Let us rewrite the above example using the String Formatting Operator '%'.


Example :


x = 3
y = 4
z = x + y
print("The added value of %d and %d is %d" % (x, y, z))


Output :



  The added value of 3 and 4 is 7

So, inside the 'print(...)' statement, there are two parts.


print("The added value of %d and %d is %d" % (x, y, z))

The left part has the actual String to be printed, with two, so called placeholders %s and %d.


'The added value of %d and %d is %d'

And the right side has the values to be placed in the above placeholder.


% (x, y, z)

Now, if you look at the output,


The added value of 3 and 4 is 7

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.


Methods to handle Strings

  1. len()

    Used to return the length of a String.

    Example :


    x = "Hello"
    print("The length of the String is ",len(x))
        


    Output :



      The length of the String is 5
Note : Please click on the below methods to get details.



Method Description
len( ) Used to return the length of a String
split( ) Used to split a string based on the value provided
splitlines( ) Used to split the string at line breaks and returns a list of Strings
lower( ) Used to convert all the letters of a String to lower case
upper( ) Used to convert all the letters of a String to upper case
replace( ) Used to replace a String with some other String
find( ) Used to search for the substring and returns its position
isnumeric( ) Used to check if all the characters are numeric. Returns true else false
isidentifier( ) Used to check if the String is an identifier. Returns true else false
islower( ) Used to check if all the characters are in lower case. Returns true else false
isupper( ) Used to check if all the characters are in upper case. Returns true else false
isspace( ) Used to check if all the characters are spaces. Returns true else false
isalnum( ) Used to check if all the characters are alpha numeric. Returns true else false
isalpha( ) Used to check if all the characters are alphabets. Returns true else false
isdecimal( ) Used to check if all the characters are decimal. Returns true else false
isdigit( ) Used to check if all the characters are digit. Returns true else false
isprintable( ) Used to check if the String is printable. Returns true else false
istitle( ) Used to check if the String is a title. Returns true else false
title( ) Used to convert each character of the word into upper case.
capitalize( ) Used to convert the forst characer of the String to upper case
format( ) Used to present the string in a proper format.
center( ) Used to return the String Centered
casefold( ) Used to convert all characters of the String to lowercase
count( ) Used to count the number of characters in the String
startswith( ) Used to check if a String starts with a specific substring
endswith( ) Used to check if a String ends with a specific substring
expandtabs( ) Used to set specific size for tabs
encode( ) Used to encode a String
index( ) Used to get the index or position of the substring inside a String
join( ) Used to join an Iterable String
translate( ) Used to return a translated String
maketrans( ) Used to return a mapping table for translation taht is later used by translate( )
rjust( ) Used to return a right justified String
ljust( ) Used to return a left justified String
strip( ) Used to trim a string
rstrip( ) Used to return right trim String
lstrip( ) Used to return left trim String
partition( ) Used to return a tuple where the string is divided into three parts
rpartition( ) Used to return a tuple where the string is divided into three parts
rfind( ) Used to search the string for a particular value.
rindex( ) Used to search the string for a particular value and returns the position/index.
rsplit( ) Used to split the string by a separator, and returns a list
zfill( ) Used to fill the string with number of 0's at the beginning.