Introduction
In the initial phase of learning any programming language, you must understand in detail one of the most important data types which is Strings. Strings are basically a series or an array of characters that includes UNICODE values from letters, numbers, special characters, etc. In this article, we are going deep on the basics of strings in python and some of their properties.
Things you'll learn:
- What are strings in python?
- Changing case in strings
- Combining or concatenation of strings
- Adding newline and tabs to strings
- Removing whitespaces in strings
- Multiline strings
- Length of a string
- Dealing with syntax errors
What are strings in python?
As discussed earlier, strings are simply a sequence of characters. Everything we write inside a single or double quote is considered as a string in python.
"I'm a string"'Yeah, me too'
The flexibility of using both single and double quotes can be useful to create apostrophes inside the strings. You can mark a single-quoted apostrophe when creating a string with double quotes and vice versa.
If you want to see a string printed in the console, just add a print statement and execute the program.
>>> print("I'm a string")I'm a stringOR>>> string = "I'm also a string inside a variable">>> print(string)I'm also a string inside a variable
Changing case in strings
While creating a string in python you don't need to bother about the structure, for instance, if you want to create a string with all its letters in uppercase, there is no need to switch on your caps lock on the keyboard, instead, there are some methods which helps you for this purpose.
Changing a string to uppercase:
>>> greeting = "Welcome to the python basics tutorial on strings">>> print(greeting.upper()) # Using upper() method to convert to uppercaseoutput:WELCOME TO THE PYTHON BASICS TUTORIAL ON STRINGS
Here the string is stored inside a variable greeting and we used the upper() method with the variable to convert the entire string to uppercase. You can simply use the upper() method to convert any string of any size to uppercase letters.
Changing a string to lowercase:
>>> greeting = "Welcome to the python basics tutorial on strings">>> print(greeting.lower()) # Using lower() method to convert to lowercaseoutput:welcome to the python basics tutorial on strings
Converting the starting letters of every string to uppercase and remaining to lowercase:
You can convert the starting letters of every word in a string to uppercase and remaining to lowercase using the title() method.
>>> greeting = "Welcome to the python basic tutorial on strings">>> print(greeting.title())output:Welcome To The Python Basic Tutorial On Strings
You can see the first letters of every word are converted to uppercase and the remaining to lowercase.
Combining or Concatenation of strings
Concatenating simply means mixing two strings together, You can simply combine two strings in python using the "+" operator
>>> print("Hello" + "World")output:HelloWorld
Here the two strings "Hello" and "World" are concatenated together using the "+" operator to form "HelloWorld". Combining two strings is useful in many cases, for instance, you can store your first name in one variable and last name in another and combine those two variables to form the full name.
>>> first_name = "Leonardo">>> last_name = "Dicaprio">>>>>> full_name = first_name + " " + last_name>>> print(full_name)output:Leonardo Dicaprio
Here the first name is "Leonardo" which is stored in the variable first_name and "Dicaprio" which is the last name stored in last_name. By concatenating the first_name and the last_name we'll get the full name "Leonardo Decaprio".
Now we know how to combine word strings, but what happens if we combine two strings with numbers?
>>> nine = "9">>> ten = "10">>> print(nine + ten)
If you get the output of the above code 910 then you're right. Since these two numbers 9 and 10 are inside double quotes they will concatenate together. But if you are curious to know how to add these two strings to get an output of 19 here is the code:
>>> nine = int("9")>>> ten = int("10")>>> print(nine + ten)output:19
What we actually did is convert the strings to integers, Here the strings "9" and "10" are converted to integers using the built-in method in python int(). Now if you execute this code it will add 9 and 10 and give you the answer 19.
Adding newlines and tabs to strings
Adding a newline or tabs simply means adding whitespaces in strings. But what are whitespaces in strings? Whitespaces are generally the non-printing characters in a string which can be useful for organizing your data.
For adding a newline in python you can use the character \n inside a string where you want to break it into a new line.
>>> print("Hello\nWorld")output:HelloWorld
Here we inserted a new line between "Hello" and "World".
Inserting a tab:
To insert a tab we can use the \t character
>>> print("Hello")>>> print("\tWorld")output:HelloWorld
Removing whitespaces in string
In some cases, the whitespaces make things complicated in our program. The python interpreter actually considers whitespaces as characters and adds them too, which results in an error. For example, the string "Hello" and "Hello " are considered two different strings by the python interpreter since the second one consists of whitespaces. So sometimes it's important to strip whitespaces from strings.
>>> greeting = "Hello World ">>> greeting.rstrip()output:'Hello World'
The unwanted whitespaces in a string can be removed by the rstrip() method in python.
Multiline Strings
So far we have talked about strings enclosed inside single and double quotes but what if you want to create multiline strings. You can't use single or double quotes for this So here we need to use three pairs of single or double quotes for creating a multiline string.
s = """Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,when an unknown printer took a galley of type and scrambled it to make a type specimen book."""print(s)
This will give the same output as organized inside the three double-quotes.
Length of a string
In any case, if you want to find the length of a string the len() method in python will help you. This function basically count all characters inside a string including whitespaces and return a number which is the length of the string
s = len("Hello World")print(s)output:11
If you count the number of letters in "Hello World" you'll end up in 10 but the len() function also includes whitespaces and return 11 as output. This is why removing unwanted whitespaces from your program is important.
Dealing with syntax errors
A syntax error occurs when some section of your code is not recognized by the python interpreter as valid python code. In strings, this may occur when we use apostrophes inside single quotes.
s = 'Hello' World'print(s)output:File "<ipython-input-20-3831694075cd>", line 1s = "Hello" World"^SyntaxError: invalid syntax
To handle this error you can add a front slash in between the apostrophes and the letter or character.
s = 'Hello\' World'print(s)output:Hello' World
