Creating and Using Strings in Python

String in Python3 can be created using both pairs of singles and double quotes. They are concatenations or secuences of characters, they can be numbers, letters or special characters as long as they are inside the quotes. 

String can be sliced, this means that you can get substrings from a string using the two slice operators:

  • String[i] This returns the character that is in the position given by i. Remember that strings start at 0.
  • String[i:j] This returns the section of characters between the given range from i to j, whitout including the upper limit. 

Strings can also be used to perform two opperations: 

  • + : this operator is the String concatenation, this means it is used to “attach” the begining of the string at the end of another string. You can make the analogy to the algebraic sum, where the result will be the adition of both components.
  • *: this is the repetition operator; this allow us to repeat the String many times as desired, just like the algebraic multiplicaction, that adds, or in our case concatenates, a certain number of the original String copies. 

For example:

>>>str = "Hello World!"  

>>>print (str)

Hello World!

>>>print (str[0])

H

>>> print (str[2:5])

llo

>>>print (str[-1])

!

>>>Print (str[::-1])

!dlroW olleH

>>> Print(str+"!!")

Hello World!!!

>>>Print(str*2)

Hello World!Hello World!

 

 

As you can see String can be seen as lists in some ways. For example the [-1] index points to the last element of the array. 

As you can see the [::-1] gives you the reversed string, but why? Well as I had said if you check lists in Python you will see that its called slicing, and what we are typing is that you will slice the string with a -1 step, this means from the last to the start. 

Most of the information was extracted from this page.

This is my of my

CC BY 4.0 Creating and Using Strings in Python by Manuel Lepe is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.