A bunch of letters and characters all together in a particular order, the only way to store any characters that are not a number, are a fundamental part of every major program.
Strings are also part of the most primitive or basic set of data-types:
|String||str||just characters in a sequence|
|Number||int, float, complex||just numbers|
|Sequence||list, tuple, range||Iterable list of values with numerical indexes for positions|
|Set||set, frozenset||Like Sequence but unordered and with duplicate elements|
|Mapping||dict||Like Sequence but indexes are characters intead of incremental numbers|
|Boolean||bool||just True or False|
|Binary||bytes, bytearray, memoryview||Ideal for low level operations|
To create a string in python just put a bunch of characters within quotes like this
"hello" or even like this
When coding a web application, everything the user types in forms it's considered a
string, even if the user types the number
2 (two) it will still be considered the string
"2" and not a real number, the developer will have to explicitely convert or parse that string into a number using the function
🔗 How to convert strings into integers with python (3 min read).
The most common use for a string is printing it using the function
Python allows to sum together strings using the plus
+ operator. The following fragment demonstrates how to add two strings to create a full name from first and last names.
In this example
"My name is " it's being concatenated with the value on the variable
You often want to know what the length (size) of a string is, for example: Twitter does not allow tweets with more than 240 characters.
After we also need to know the value of the string in a particular position, for example: If a string ends with a question mark it's probably a question:
☝ This method of character extraction on strings is very similar to the one used on lists to extract an element from a particular position in the list.
You can also extract several characters at once. The range of the method starts with the index of the first character to be extracted and ends with the index AFTER the last character to be extracted:
If you want to compare two strings you can use the
== (double equal) and it will return
True if the strings are EXACTLY the same, string comparison is case sensitive, "Bob" is not equal to "bob".
☝ it is good practice to always lowercase strings before comparing them with others, that way we will avoid missing case sensitive differences.
If you want to learn more, we suggest you start practicing instead of reading because there is nothing much to read about strings, here is a small 3 min video explaining strings.
All rights reserved, 4Geeks LLC 2021. Read more about 4Geeks and what we are going here.