Definition of String in Python
A string is a data type that is used to describe textual content in different programming languages.
In Python, a string is a sequence of Unicode characters, but there is no single character data type, so it’s also a string, which has a length of 1. Unicode was introduced to include every character. Also it brings uniformity in encoding.
To create strings you need to enclose characters inside a single quote, double-quotes or triple-quotes (in cases spanning strings over multiple lines). Also strings don’t have any limits in length or using upper-case letters. Actually, <str> represents the Python string class. In accordance, the str() function can convert a value into a string data type.
str_single_quotes = 'Welcome to KoderShop' print(str_single_quotes) #output: #Welcome to KoderShop
str_double_quotes = "Welcome to KoderShop" print(str_double_quotes) #output: #Welcome to KoderShop
str_triple_quotes = '''Welcome to KoderShop''' print(str_triple_quotes) #output: #Welcome #to #KoderShop
String Manipulation in Python
String manipulation means that you can change something in the string. To do this you need built-in string Python methods.
You already know how to create a string so here are examples how to access string characters and how to know the length of it.
Example of accessing:
example = "Hello KoderShop" character = example[6] print(character) #output #K
Example of len():
example = "Hello KoderShop" print(len(example)) #output #15
There are 47 built-in string methods in Python.
Upper() and lower() Methods
Starting from the base there are a few functions that can make letters in the string uppercase and lowercase. They are upper() function and lower() function and also they are capitalize() method that makes only first letter uppercase.
Examples of these string operations in Python:
example = "python is a masterpiece!" print(example.capitalize()) #output: #Python is a masterpiece!
example = "Python is a masterpiece!" print(example.upper()) #output: #PYTHON IS A MASTERPIECE!
example = "PYTHON IS MASTERPIECE..." print(example.lower()) #output: #python is masterpiece...
Moreover if you want to capitalize every word in your sentence, there comes the title() function, obviously used for titles in your articles.
example = "String methods in Python" print(example.title()) #output: #String Methods In Python
Swapcase() Method
If you want to switch lowercase letters to uppercase and vice versa in a string, you can use swapcase() function.
example= "kODERsHOP" print(example.swapcase()) #output: #KoderShop
Isupper() and islower() Python String Operations
To check the previous functions we can use these methods. Isupper() is used to check letters for their uppercase. And the same thing is with islower(). They both return boolean types.
example = "PYTHON IS MASTERPIECE..." print(example, "is uppercase:", str(example.isupper())) #output: #'PYTHON IS MASTERPIECE...' is uppercase: True
example = "PYTHON IS MASTERPIECE..." print(example, "is lowercase:", str(example.islower())) #output: #'PYTHON IS MASTERPIECE...' is lowercase: False
Isalnum(), isalpha(), isdecimal() String Functions Python
Isalnum() Method
This function we can use for checking if the string has numeric and alphabetical symbols. It can be useful, for example, for passwords.
example = "ABCDEFJHIJKLMOPQRSTUVWXYZ" print(example, "contains symbols from alphabet:", str(example.isalnum())) #output #ABCDEFJHIJKLMOPQRSTUVWXYZ is an alphabetical order: True
example = "123@34" print(example, "contains only numbers:", str(example.isalnum())) #output #123@34 contains only numbers: False
Isalpha() Method
This function you can use for checking whether our string has only alphabetical symbols.
example = "ABCD_EFJHIJKLMOPQRSTUVWXYZ" print(example, "contains symbols from alphabet:", str(example.isalnum())) #output #ABCD_EFJHIJKLMOPQRSTUVWXYZ is an alphabetical order: False
Isdecimal() Method
Obviously, the name of the method says its operation. It checks whether our string has only tenfold numbers:
example = '_54' print(example.isdecimal()) example = '54' print(example.isdecimal()) #output #False #True
Python String Functions center(), rjust(), ljust()
Center() Method
Actually, this function pads your string variable using default (“Space”) or specified characters. It tries to center your string text into the given length.
example = "Hello, world!" new_example = example.center(30) print('|' + new_example + '|') #output: #| Hello, world!
As we can see, our “Hello world!” is centered between two vertical bars. Here is one more example to see how it works:
example = "Hello, world!" new_example = example.center(30, '=') print('|' + new_example + '|') #output: #|========Hello, world!=========|
We have used the equals sign as a filling symbol in this example.
Rjust() and Ljust() String Python Methods
It works the same as center() string function python but pads your string on the right side using default symbols(‘Space’) or symbols that are written in attribute.
Ljust() obviously is the same as rjust() function but pads on the left side.
example = "Hello, world!" new_example = example.rjust(30) print('|' + new_example + '|') #output: #| Hello, world!|
example = "Hello, world!" new_example = example.ljust(30) print('|' + new_example + '|') #output: #|Hello, world!
Count() Method
This function is one of python string built in functions that can return how many times the given text has occurred. The name of the function says what it means.
example = "hello, my friends, hello..." print(example.count("hello")) #output: #2
but:
example = "Hello, my friends, hello..." print(example.count("Hello")) #output: #1
So, it is very strict about the case of given letters.
Another thing about count() function in Python is that you can give the indexes between which it should count:
example = "hello, my friends, hello..." print(example.count("hello", 0, 5)) #output: #1
0 and 5 are indexes of letters used for our interval.
example = "hello, my friends, hello..." print(example.count("hello", 0, 27)) #output: #2
Encode() Method
Factually, encoding is converting text that is written in one system language into another. Being a simple person you can use character UTF-8 encoding for your descriptions or texts. It is good in encoding a single character to any you want to use. This Unicode easily helps you in everything. That’s why creating HTML websites or PC systems need to have it written inside as it removes tracking for right conversion.
But anyway there can be situations where you need not UTF-8 but another. That’s where one of python strings methods, the encode() method comes in.
example = "python" print(example.encode('cp037')) #output: #b'\x97\xa8\xa3\x88\x96\x95'
Python String Function Endswith()
Endswith() method is used for checking if the string variable has the symbols we have given. Again the name of the function can say all what it means.
example = "hello, my friends, hello..." example = "helloworld" print("Does our first string have this ending?", str(example.endswith("world"))) example = "helloworld." print("Does our second string have this ending?", str(example.endswith("world"))) #output: #Does our first string have this ending? True #Does our second string have this ending? False
In output “this ending” means “world” so it helps us to see how the endswith() function works. It is strict to written symbols, so if there is at least one comma or dot, it counts.
Find() and index() String Functions in Python
Find() Method
One of the base functions used for string is find(). It is easy to use and is very powerful. Obviously you can use it for finding words in written strings.
example = 'Hello, KoderShop' print(example.find('KoderShop')) #output #7
In this python string method example the start of ‘KoderShop’ is on the 7th symbol. But if the find() function can`t find anything it returns ‘-1’:
example = 'Hello, KoderShop' index = example.find('hello') print("'hello' word is found at:", index) index = example.find('kodershop') print("'kodershop' found at index:", index)
Another good example of find() usage in string is:
example = 'Hello, KoderShop' word = 'Wikipedia' if example.find(word) != -1: print( word, "contains in string") else: print( word, "doesn't contain in string") #output #Wikipedia doesn't contain in string
Index() Method
index() method itself helps you to find the first index where the given string is located. Here is an example of this string command python:
example = 'python string functions examples' print(example.index('but')) #output: #ValueError: substring not found
And obviously, here we can see the difference between find() and index() string functions in Python. When find() returns ‘-1’, the index() returns an exception. It is the only difference. In another it is the same as find().
Python String format Method
If you want to have a possibility to add and edit words anywhere in the string, you can use the format() string method.
example = "This article is written by {}" print(example.format("KoderShop")) #output: #This article is written by KoderShop
Additionally for using more than one pair of brackets it would be better to add placeholder values inside the brackets.
example = "This article is written by {company}. It is about {topic}." print(example.format(company = "KoderShop", topic = "string methods")) #output: #This article is written by KoderShop. It is about string methods.
Format_map() Method
With this method you can have a dictionary with words and their keys and use these keys to have access to the words in the string. It has the same python string operation as the built-in dictionaries in Python 3.
dictionary = {'company':'KoderShop', 'topic':'string methods'} print("This article is written by {company}. It is about {topic}.".format_map(dictionary)) #output: #This article is written by KoderShop. It is about string methods.
Python String Methods split() and rsplit()
Split() Method
It allows you to split the words using space, semicolon or other symbols. For example, having one string you can have a list of words from it.
example = '2022 – the best year'.split() print(example) #output: #['2022', '–', 'the', 'best', 'year']
example = '2022 – the best year'.split('–') print(example) #output: #['2022 ', ' the best year']
You can see how we use ‘t’ as separator below:
example = '2022 - the best year'.split('t') print(example) #output: #['2022 - ', 'he bes', ' year']
Split() function and its own attributes split(separator, maxsplit) :
maxsplit()
maxsplit() is the attribute that makes the maximum number of splits that must be done. It is a very useful one.
example = '2022 - the best year'.split(' ', maxsplit=1) print(example) #output: #['2022', '- the best year']
Here we used the space as a separate symbol and made the maximum amount of splits 1.
separator()
separator() obviously is our separate symbol that we used before. It can be as ‘ ‘, as ‘t’ and even as ‘#’ !
example = '2022#-#the#best#year'.split('#') print(example) #output: #['2022', '-', 'the', 'best', 'year']
Rsplit() Method
It allows you to split the words the same as the split() method that was mentioned before, but it does it starting from the right side. The clear example of it is using the maxsplit().
For instance, it can be used when we have a maxsplit() attribute that equals ‘1’ and we want to split only one word at the end.
example = '2+2+2+3'.rsplit('+', maxsplit=1) print(example) #output: #['2+2+2', '3']