Strings have already been discussed in the Data Types section; But the prevalence of strings is so high that it is necessary to make a separate post. So here we will discuss Python strings and its built-in functions in detail.

In last blog post we showed just assigning string and printing it, here we will start from that.

Multiline String

When a string is enclosed in double quotes, it is usually treated as a line; But in practice, it may be necessary to write multiple lines, in that case, if the string is written inside three double quotes or three single quotes, it will appear in the output like that if it is written in multiple lines. Lets see an example –

# This program is an example of multi-line string in python
  
str1="""Hello everybody,
This is a multi-line string,
using triple double quote"""

str2='''Hi guys,
This is a multi-line string,
using triple single quote'''

print(str1) # Printing str1

print(str2) # Printing str2

Result:

Hello everybody,                                                                                    
This is a multi-line string,                                                                        
using triple double quote                                                                           
Hi guys,                                                                                            
This is a multi-line string,                                                                        
using triple single quote

The above example shows printing a multi-line string.

Since indentation is very important in Python, a string cannot be written on more than one line. Three double or single quote are used to solve this problem.

String Manipulation

Strings in Python are basically sequentially arranged one after the other like an array, so if you want, you can access a specific character or string separately according to their order. Not seeing how to access a particular character-

# This program is an example to access a specific character in python
  
name="Python"

print(name[0]) # Printing the first character

Note that there is no character data type in Python. A character in a string means it is a character.

Result-

P

5th line uses name[0]. That is, instead of using the full name variable, the first character of that variable is used.

In this way, the concept of sorting one by one is called indexing in programming language. Indexing starts at 0, not 1.

Slice a specified part from a string

Let’s say, we want to retrieve a specific part of a string instead of a specific character. For this, the colon operator (:) is used in Python. Lets see an example-

# This program is an example to slice a specific portion from a string in python
  
name="Hello Python"

print(name[6:8]) # Printing the sliced string

Result:

Py

5th line uses colon operator. The rule of thumb is to use the colon with the position we want to slice from and the position we want to end with.

Note that a space is also a character.

Calculate the position from the opposite direction

So far we have followed hierarchy for calculating or indexing positions i.e. from first to last, now we will follow hierarchy i.e. coming from last to first, in a word counting from opposite direction. It is also called negative indexing.

# This program is an example of negative indexing in python
  
name="Hello Python"

print(name[-1]) # Printing a single character using negative indexing

print(name[-6:-4]) # Printing the sliced string using negative indexing

Result-

n                                                                                                   
Py

The rule is to count from the end. Everything else is the same as before.

String concatenation

Concatenating one or more strings together is very important and practical. In Python this is easily done with the plus operator (+). lets see an example –

# This program is an example of string concatenation in python
  
str1="Hello"
str2="Python"
finalstr=str1+" "+str2

print(finalstr) # Printing the concatenated string

Result:

Hello Python

In line 5 we concatenate the three strings using the plus operator.

Note that there is no space between the 3rd and 4th line strings, so a space character ” ” is used. It is also a string.

Repeating a string

The multiplication operator (*) is used to iterate over multiple strings. It will be easy to understand by looking at an example –

# This program is an example of repeating a string in python
  
str1="Python"
str2=str1*2
str3=str1*3

print(str2) # Repeating 2 times
print(str3) # Repeating 3 times

Result:

PythonPython                                                                                        
PythonPythonPython

That is, the number of times to be printed must be given after the * operator.

Escape character

Let’s see an example first. Let’s say we want to use a string that contains the text – I like “Frozen” movie.

# This program is an example of an escape character in python
  
print("I like "Frozen" movie.")

Result:

    print("I like "Frozen" movie.")
                        ^
SyntaxError: invalid syntax

An error has occurred for a valid reason. Since strings start and end with double quotes, Python cannot decode any double quotes. Escape character is introduced to solve this problem. Rewrite the program –

# This program is an example of an escape character in python
  
print("I like \"Frozen\" movie.")

Result:

I like "Frozen" movie.

Here is our desired result.

In the 3rd line we used a backslash () character, the escape character is used to use characters that are not normally used in strings. Enter the desired character with a backslash. Python has multiple escape characters.

Escape CharacterDescription
\\Creates a backslash
\nCreate a new line
\aMake an audible sound
\bCreate a backspace
\tCreate a Tab
\xnnHexadecimal number

Let’s take a look at one example of these.

# This program is an example of an escape character in python
  
print("This is a backslash \\") # \\
print("This is a \nnewline") # \n
print("This is an audible sound \a") # \a
print("This is a back\bspace") # \b
print("This is a\tTab") # \t
print("This is a hexadecimal representation: "+"\x50\x79\x74\x68\x6f\x6e") # \xnn

Result:

This is a backslash \
This is a 
newline
This is an audible sound 
This is a bacspace
This is a       Tab
This is a hexadecimal representation: Python

String methods

Additionally, Python’s string library is quite rich. Here, we will briefly learn about some methods for string manipulation (in alphabetical order).

capitalize()

This function capitalizes a string, meaning it converts the first character of any given string to uppercase.

#This is an example of string capitalize() method in python

teststring="hello python" # capitalize()

print(teststring.capitalize())

Result:

Hello python

The first character has been capitalized.

casefold()

This function transforms all characters within a string to lowercase.

#This is an example of string casefold() method in python

teststring="Hello Python" # casefold()

print(teststring.casefold())

Result:

hello python

It converts the ‘H’ in “Hello” and the ‘P’ in “Python” to lowercase.

center()

This function centers a string. It takes two parameters; the first is mandatory and the second is optional. The first parameter is a number indicating the width the string should occupy; the second is a character string that fills the space.

#This is an example of string center() method in python

teststring="Python" 

print(teststring.center(10)) # center()

print(teststring.center(10,"*")) # center() with padding character

Result:

  Python                                                                                                                      
**Python**

On line 7, we’ve used ‘*’ which results in filling the spaces with asterisks.

count()

This method counts how many times a specific substring occurs within a string.

#This is an example of string count() method in python

teststring="Python is relatively easy language to learn" 

print(teststring.count("la")) # count() function

Result:

2

In our test string, “la” appears twice. This function can also be applied to a specific part of the string.

#This is an example of string count() method in python

teststring="Python is relatively easy language to learn" 

print(teststring.count("la",20,40)) # count() function

Result:

1

endswith()

This method determines whether a string ends with a specified substring, returning True or False as a result.

#This is an example of string endswith() method in python

teststring="Python is relatively easy language to learn" 

print(teststring.endswith("n")) # endswith() function

Result:

True

This indicates that the string indeed ends with ‘n’. The function can also operate over a specified part.

The explanations for additional string manipulation methods follow the same structure, providing an easy-to-understand guide on each function’s utility and usage in Python.

#This is an example of string endswith() method in python

teststring="Python is relatively easy language to learn" 

#print(teststring.endswith("n")) # endswith() function
print(teststring.endswith("n",20,40)) # endswith() function

Result:

False

This means that in the specified range, the string does not end with ‘n’.

expandtabs()

This function is used to set the size of tabs in a string. If no argument is provided, it defaults to the standard tab size, but if a value is specified, the tab size will adjust accordingly.

#This is an example of string expandtabs() method in python

teststring="P\ty\tt\th\to\tn" 

print(teststring.expandtabs()) # expandtabs() method -default

print(teststring.expandtabs(2)) # expandtabs() method -size 2

print(teststring.expandtabs(10)) # expandtabs() method -size 10

Result:

P       y       t       h       o       n                                                                                                                                          
P y t h o n                                                                                                                                                                        
P         y         t         h         o         n

find()

This method is used to search for a substring within a string; if found, it returns the position, otherwise it returns -1.

This method can also be applied to a specific section of the string.

#This is an example of string find() method in python

teststring="Hello Python" 

print(teststring.find("Py")) # find() method -default

print(teststring.find("Py",1,5)) # find() method within range

Result:

6                                                                                                                                                                                  
-1

We got a result of 6 for the sixth line because that’s where our desired result is located; the next attempt resulted in -1 because there is no ‘Py’ in that part of the string.

index()

This method is similar to the find() method, except it throws an exception if the substring is not found.

#This is an example of string index() method in python

teststring="Hello Python" 

print(teststring.index("Py")) # index() method -default

print(teststring.index("Py",1,5)) # index() method within range

Result:

6                                                                                                                                                                                  
Traceback (most recent call last):                                                                                                                                                 
  File "main.py", line 7, in <module>                                                                                                                                              
    print(teststring.index("Py",1,5)) # find() method within range                                                                                                                 
ValueError: substring not found 

Thus, we received a result of 6 for the fifth line, but an error occurred for the seventh line.

isalnum()

This method is used to check if a string is alphanumeric. It verifies whether the string contains only letters (a-z/A-Z) and numbers (0-9) without any other characters. If the string is alphanumeric, it returns True; otherwise, False. Let’s see an example:

#This is an example of string isalnum() method in python

teststring="HelloPython" 
teststring2="Hello Python" 

print(teststring.isalnum()) # isalnum() method

print(teststring2.isalnum()) # isalnum() method

Result:

True                                                                                                                                                                               
False

Here, we see that test_string only contains alphabetic characters, hence the result is True. On the other hand, test_string2 includes a space between “Hello” and “Python”, which is not an alphanumeric character, resulting in False.

isalpha()

Similar to the previous method, this method checks if a string contains only alphabetic characters.

#This is an example of string isalpha() method in python

teststring="Hello" 
teststring2="Hello20" 

print(teststring.isalpha()) # isalnum() method

print(teststring2.isalpha()) # isalnum() method

Result:

True                                                                                                                                                                               
False

Here, test_string is purely alphabetic, resulting in True, whereas test_string2 includes numerics, making it False.

isdecimal()

This method checks if a string consists solely of decimal numbers.

#This is an example of string isdecimal() method in python

teststring="55"

print(teststring.isdecimal()) # isdecimal() method

Result:

True

isdigit()

This method determines if a string contains only digits (0-9).

#This is an example of string isdigit() method in python

teststring="5"

print(teststring.isdigit()) # isdigit() method

Result:

True

isidentifier()

This method checks if a string is a valid identifier, meaning it can be used as a variable name in programming.

#This is an example of string isidentifier() method in python

teststring="variable"
teststring2="123"
teststring3="string name"

print(teststring.isidentifier()) # isidentifier() method
print(teststring2.isidentifier()) # isidentifier() method
print(teststring3.isidentifier()) # isidentifier() method

Result:

True                                                                                                                                                                               
False                                                                                                                                                                              
False

In this case, “variable” is a valid identifier, while “123” and “string name” are not, due to starting with a digit and containing spaces, respectively.

islower()

This method checks if all characters in a string are lowercase.

#This is an example of string islower() method in python

teststring="Hello"
teststring2="hello123"
teststring3="string name"

print(teststring.islower()) # islower() method
print(teststring2.islower()) # islower() method
print(teststring3.islower()) # islower() method

Result:

False                                                                                                                                                                              
True                                                                                                                                                                               
True

Here, “Hello” has an uppercase ‘H’, so it returns False, but the other two examples return True as they are entirely in lowercase, including numbers and spaces, which are neutral in case.

isspace()

This method checks if a string is composed only of whitespace.

#This is an example of string isspace() method in python

teststring="Hello"
teststring2="    "
teststring3="      h      "

print(teststring.isspace()) # isspace() method
print(teststring2.isspace()) # isspace() method
print(teststring3.isspace()) # isspace() method

Result:

False                                                                                                                                                                              
True                                                                                                                                                                               
False

Only the string that consists solely of spaces returns True.

isupper()

This method checks if all characters in a string are uppercase.

#This is an example of string isupper() method in python

teststring="Hello"
teststring2="HELLO"

print(teststring.isupper()) # isupper() method
print(teststring2.isupper()) # isupper() method

Result:

False                                                                                                                                                                              
True

“HELLO” is entirely in uppercase, hence True, whereas “Hello” contains a lowercase ‘e’, resulting in False.

join()

This method is used in Python to concatenate any iterable data type using a specific string.

#This is an example of string join() method in python

teststring="Hello"
testlist=["Hello","Python"]
testtouple=("C","Python")
testset={"Anaconda","Python"}
testdict={"name":"Python","feature":"OOP"}

print("*".join(teststring)) # join() method in string
print("*".join(testlist)) # join() method in list
print("*".join(testtouple)) # join() method in touple
print("*".join(testset)) # join() method in touple
print("*".join(testdict)) # join() method in dictionary

Result:

H*e*l*l*o                                                                                                                                                                          
Hello*Python                                                                                                                                                                       
C*Python                                                                                                                                                                           
Python*Anaconda                                                                                                                                                                    
name*feature

The join method links elements within the iterable through the specified delimiter, here being the asterisk (*).

len()

This method determines the number of characters or length of a string.

#This is an example of string len() method in python

teststring="Hello python learners!!!"

print(len(teststring)) # len() method

Result:

24

lower()

This method is used to convert a string into lowercase.

#This is an example of the string lower() method in python

teststring="Hello Python"

print(teststring.lower()) # lower() method

Result:

hello python

lstrip()

This method removes specific characters from the beginning of a string. It typically removes spaces, but if a parameter is given, it removes the specified characters instead.

#This is an example of string lstrip() method in python

teststring="     Hi    "
teststring2="Hello Python"

print(teststring.lstrip()) # lstrip() method -default value
print(teststring2.lstrip("oHel")) # lstrip() method -custom value

Result:

Hi                                                                                                                                                                                 
 Python

In the seventh line, we used parameters which caused the first word to be removed.

partition()

This method splits a string into three parts around a specified substring. It divides the string into a tuple containing the part before, the separator itself, and the part after the separator.

#This is an example of string partition() method in python

teststring="Hello Python Learners!!!"

print(teststring.partition("Python")) # partition() method

Result:

('Hello ', 'Python', ' Learners!!!') 

replace()

This method is used to replace one substring in a string with another.

#This is an example of string replace() method in python

teststring="Hello Python2 Learners!!!"

print(teststring.replace("Python2","Python3")) # replace() method

Result:

Hello Python3 Learners!!!

Here, “Python2” was replaced by “Python3”.

split()

This method divides a string into a list at each instance of a specified separator. By default, it splits at any whitespace if no parameters are specified.

#This is an example of string split() method in python

teststring="Hello Python Learners, Welcome to the Python Tutorial"

print(teststring.split()) # split() method -default value
print(teststring.split(",")) # split() method -specified value

Result:

['Hello', 'Python', 'Learners,', 'Welcome', 'to', 'the', 'Python', 'Tutorial']                                                                                                     
['Hello Python Learners', ' Welcome to the Python Tutorial']

slitline()

This method divides a string at line breaks, creating a list of each line.

#This is an example of string splitlines() method in python

teststring="""Hello Python Learners,
Welcome to the Python Tutorial"""

print(teststring.splitlines()) # splitlines() method

Result:

['Hello Python Learners,', 'Welcome to the Python Tutorial']

startswith()

This method checks if a string starts with a specified substring.

#This is an example of string startswith() method in python

teststring="Hello Python"

print(teststring.startswith("Hel")) # startswith() method

Result:

True

strip()

This method removes specified characters from both the beginning and end of a string. If no arguments are provided, it only removes whitespace.

#This is an example of string strip() method in python

teststring="     Hi    "
teststring2="Hello Python Learners!!!"

print(teststring.strip()) # strip() method -default value
print(teststring2.strip("elHoLarns!")) # strip() method -custom value

Result:

Hi                                                                                                                                                                                 
 Python  

swapcase()

This method converts all lowercase letters in a string to uppercase and all uppercase letters to lowercase.

#This is an example of string swapcase() method in python

teststring="Hello Python"

print(teststring.swapcase()) # swapcase() method

Result:

hELLO pYTHON

title()

This method capitalizes the first letter of every word in a string, making it suitable for titles.

#This is an example of string title() method in python

teststring="Hello python learners!!!"

print(teststring.title()) # title() method

Result:

Hello Python Learners!!!

upper()

This function converts all lowercase letters in a string to uppercase.

#This is an example of string upper() method in python

teststring="Hello python learners!!!"

print(teststring.upper()) # upper() method

Result:

HELLO PYTHON LEARNERS!!!

zfill()

This method pads a string on the left with zeros until it reaches the specified length.

#This is an example of string len() method in python

teststring="Hello python"
teststring2="50"

print(teststring.zfill(20)) # len() method using 20 padding
print(teststring2.zfill(20)) # len() method using 20 padding

Result:

00000000Hello python                                                                                                                                                               
00000000000000000050
0 0 votes
Article Rating
0
Would love your thoughts, please comment.x
()
x