No strings attached

--Originally published at Programming

Creation and use of Strings

Today, we are going to be talking about a very simple topic, how to create and use strings in Python. You may think that you’ve already mastered the art of strings, but you would be surprised if you knew that you don’t know the full potential of strings. Let’s begin.

A string is one of the most popular data types in Python, they can be created by surrounding a sentence in double quotes “” or single quotes ”. You use them when you print them out to the console and when you assign a string to a variable.

Access substrings in Strings

Unlike other languages, Python does not support the character type, so any value that is contained within a string is going to be called substrings. To access is pretty simple, since it is the same as if we had a list and we wanted to get the value at i position. 1.png

Slicing Strings

Just like with lists, we can slice a string by using the square brackets along with the indices to obtain the new string.

2.png

3.png

Non Printable Characters

If you use a non printable character inside a string, they are not going to be printed. These non printable characters, also called escape characters, are not going to be printed by the console, instead they are going to make some changes to you string. Don’t worry if you don’w understand yet, let me use some examples.

4.png

5.png

Special Operators

Here is a list with examples of the most important string operators that you are eventually going to be using.

6.png

7.png

Built-in String Methods (Functions)

As you should remember, lists have their methods to manipulate and insert data. Some examples for those methods are the append() or the insert(). But fortunately strings have also their own set

methods that can be used whenever you want. We are going to list some of the most important ones explaining their functionality.

  • count (substring, begin, end): Counts and returns how many times the substring given was found in the String within the range given
  • endswith (suffix, begin, end): Returns true if a string ends with the suffix given
  • find (substring, begin, end): Determines if the substring is within the string and, if found, it returns its position. The method will return the first substring it finds, if not fount, it will return -1.
  • isdigit(): Returns true if the string contains only digits
  • len(string) returns the length of the string