String Manipulation in Python: Functions, Indexing, Concatenation, and More.

String Manipulation in Python: Functions, Indexing, Concatenation, and More.


Introduction :

Today in this article, we will discuss the contents of strings in Python and explain its functions in detail. We'll explore how to represent them using multiline strings and triple quotes.


This allows us to write strings spanning multiple lines, ensuring better code readability. We will show an example of multiline strings and see its output.


The concept of indexing in Python strings will also be covered, which allows us to access individual characters or substrings based on their position in the string.


We will learn how to access certain characters and understand the indexing process, which starts with 0 instead of 1.


Additionally, we will discuss string manipulation techniques, such as extracting a specific segment from a string using slicing.


By employing the colon operator, we can extract a substring from a larger string based on the desired start and end position.


String concatenation, the process of combining multiple strings into a single string, will be covered using the plus operator.


We will explain how to concatenate strings and highlight the importance of considering spacing between concatenated strings.


The article will provide an overview of some commonly used string methods available in Python's string library.


These functions include Capitalize(), CaseFold(), Center(), Count(), EndsWidth(), ExpandTab(), Find(), Index(), IsAlnum(), IsAlpha(), IsDecimal(), IsDigit().  is included.  , isidentifier(), islower(), isspace(), isupper(), join(), len(), lower(), lstrip(), partition(), and more. 


Each function will be explained with examples to demonstrate its functionality and usage.


Strings in Python


Our previous article discussed strings in the data type section; But the prevalence of the string is so high, that itis necessary to make a separate episode. So here we will discuss Python strings and its built-in functions in detail.

Read more: Python byte code, variables, oparators

In that article we only showed how to assign string and print 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 reality it may be necessary to write more than one line, in that case if the string is written inside three double quotes or three single quotes then it will appear in the output like that.


See an example –


 str1=" " "Hello everybody, This is a multi-line string, using triple single quote" " "


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


 print(str1)


 print (str2) 


 Result

Hello everybody, This is a multi-line string, using triple single 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 coats 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.

Lets see how to access a particular character-


  name="Python"


 print(r)(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


'name[0]' is used.  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.


Cut a specified part from a string


Let's say, we want to retrieve a specific part of a string instead of a specific character from the entire string.  For this, the colon operator '(:)' is used in Python.


See an example-


 name="Hello Python"


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


 Result-


 Py


2nd line uses colon operator.  The rule of thumb is to use the colon with the position we want to cut 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. from last to first, in a word counting from opposite direction.  It is also called negative indexing.


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 '(+)'.  Let's  see an example –


str1="Hello"


str2="Python"


finalstr=str1+" "+str2


 print (finalstr) # Printing the concatenated string


Result-


 Hello Python


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


 Note that there is no space between the strings in the 1st and 2nd lines, so a space character ” ” is used in the 3rd line.  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 –


 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 look at an example first. Let's say we want to use a string that contains the text – I like “Frozen” movie.


 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 to solve this problem.

Rewrite the program again –

 

print("I like \"Frozen\" movie.")


 Result-


 I like "Frozen" movie.


 That is, we got the desired result.


In the 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.


HTML Table Generator

Escape character description 
 \\ Creates a backslash.
 \n will create a new line.
 \a Make a word.
 \b will create a backspace.
 \t A tab will be created.
 \xnn Hexadecimal number.



Lets see an example of these-


 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 backspace 

This is a Tab 

This is a hexadecimal representation: Python


 String methods


Also Python's string library is very rich.  Here's a brief look at some of the string manipulation functions (in alphabetical order) –


  capitalize()


 This function capitalizes a string, that is, it will make the first letter of a string uppercase.


 teststring="hello python" # capitalize()


 print(teststring.capitalize())


 Result –


 Hello python


 Here the first letter is capitalized.


casefold()


 This function converts all characters within a string to lowercase.


 teststring="Hello Python" # casefold()


 print(teststring.casefold())


 Result-


 hello python


That is, the 'H' of Hello and the 'P' of Python have been converted to lowercase letters.


center()


This function center aligns a string.  It has two parameters, one mandatory and the other optional. The first is a number, which indicates how much space the string will display;  The second parameter is a character string with which to fill the space.


 teststring="Python"


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


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


 Result-


    Python 

**Python**


In the 3rd line we have used '*' due to which the blank spaces are filled with' * 'in the result.


count()


 This method determines how many times a given string occurs in a sentence.


 teststring="Python is relatively easy language to learn"


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


 Result-

 2


The test string we have has "la" twice so here the result is 2.  This function can also be applied to a specific segment.


teststring="Python is relatively easy language to learn"


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


 Result-


 1


  endswith()


This method determines whether or not a string is at the end of a string and returns a True or False result.


teststring="Python is relatively easy language to learn"


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


 Result-


 True


 That is, the string ending with 'n' is true.


This function also works for a specific part like the previous function.


teststring="Python is relatively easy language to learn"


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


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


 Result-


 False


 That is, the range used here is a string that does not end with 'n'.


expandtabs()


This function is used to set the size of Tab.  If no arguments are given to the function it will default to tab, but if value is given the Tab will be sized accordingly.


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 find a string within another string;  Returns its position if found otherwise -1 value.


This method can also be used for a specific part as before.

 

teststring="Hello Python"


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


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


 Result-

 6

-1


For the 2nd line we get the result 6 because this is where we got the desired result;  The next one gets -1 because there is no 'Py' string in this part.


index()


This method is similar to the find() method, except that if no match is found, an exception will be thrown.


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 3, in <module> 


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


ValueError: substring not found


 i.e for line 2 the result is 6 but for line 3 an error is returned.


isalnum()


This method is used to check whether a string is alphanumeric or not.  That is, it checks whether a string contains anything other than alphabet (a-z/A-Z) and number (0-9).  Returns True if it is alphanumeric, otherwise False.


See an example –


teststring="HelloPython"

teststring2="Hello Python"


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


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


 Result-

 1True

 False


Here we can see that 'teststring' has only alphabetic characters so the result is "True".  On the other hand, there is a "space" character between "Hello" and "Python" in teststring2" which is not an alphanumeric character, but a special character;  That's why the result is False.


isalpha()


 Like the previous method, this method checks whether a string contains alphabetic characters.


teststring="Hello"

teststring2="Hello20"


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


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


 Result-

  True

  False

 

"Teststring" returns "True" because it is an alphabetic character and "teststring2" returns "False" because it is an alphanumeric string.


isdecimal()


If any string is decimal i.e if any number then True otherwise False.


teststring="55"


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


 Result-

 True


  isdigit()


If any string is a digit i.e. any number between 0-9 then True otherwise False.


teststring="5"


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


 Result-


 True


  isidentifier()


If a string is a valid identifier i.e. if we can use it as a variable name then this method will be True otherwise False.


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


islower()


This method checks whether the characters in a string are lowercase. True if all are lowercase otherwise False.


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


Note here: that no space or numeric value is considered by this method. It only validates characters.


String Manipulation in Python: Functions, Indexing, Concatenation, and More.



isspace()


Used to check if a string consists only of spaces.


teststring="Hello"

teststring2="    "

teststring3="      h      "


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


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


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


Result-

False

True

False


isupper()


True if all characters in a string are uppercase otherwise False.


teststring="Hello"

teststring2="HELLO"


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


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


 Result-

 False

 True


  join()


This method concatenates any Python iterable data type with a specified string.


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


len()


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


 teststring="Hello python learners!!!"


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


 Result-


 24


  lower()


This method is used to convert a string to lowercase.


teststring="Hello Python"


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


 Result-

 hello python


  lstrip()


This method deletes a specified character. Normally it removes spaces, but if given an argument it removes those characters.


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 4th line we used some parameters due to which the first term is deleted.


partition()


This method splits a string into three parts.  A total of three parts are split before and after the desired string, including where it is.


 teststring="Hello Python Learners!!!"


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


 Result-


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


  replace()


This method is used to replace one string with another string.


 test string="Hello Python2 Learners!!!"

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


 Result-


 Hello Python3 Learners!!!


 Here python2 is replaced by Python3.


split()


This method is used to split a given string into smaller parts.  Generally it breaks down into smaller words;  But if you give a specific value to the argument, it will break it accordingly.


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 is used to split a string into multiple lines.


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 is used to check if a string starts with another string.


teststring="Hello Python"


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


 Result-

 True


  strip()


This method removes specified characters from the beginning or end of a string.  If no arguments are used it only removes spaces, if arguments are used it removes those specific characters.


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 lowercase letters to uppercase and uppercase letters to lowercase.


teststring="Hello Python"


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


 Result-


 hELLO pYTHON


 title()


Converts the first letter of all words in a string to uppercase.


teststring="Hello python learners!!!"


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


Result-


Hello Python Learners!!!



upper()


This function converts lowercase letters to uppercase letters.


teststring="Hello python learners!!!"


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


 Result-


 HELLO PYTHON LEARNERS!!!


 zfill()


This method is used to fill the leading digits of a string with "0". Given a number as an argument, the output character will be this number. The given number will sit to the right of all and the rest will be filled with '0's.


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


Conclusion:

This article provides a comprehensive overview of strings in Python and their various functions. It starts by explaining multiline strings and how to represent them using triple quotes, which improves code readability.


The concept of indexing is covered, allowing access to individual characters or substrings based on their position in the string. String manipulation techniques such as slicing, concatenation, and repetition are explored, demonstrating different ways to modify and combine strings.


The article also introduces several commonly used string methods available in Python's string library. Each method is explained with examples to illustrate its functionality and usage.


Throughout the article, the importance of understanding string operations and their applications in Python programming is emphasized.


By mastering these concepts and functions, developers can manipulate strings effectively, extract desired information, and perform various operations on textual data.


FAQ


Q: What is negative indexing in Python strings?


The article introduces negative indexing, which allows counting positions from the end of a string.


It explains how to access characters or substrings using negative indices.


Q: How can I represent multiline strings in Python?


To represent multiline strings, you can enclose the string within triple quotes (`"""` or `'''`).


This allows you to write strings spanning multiple lines for better code readability.


Q: How does indexing work in Python strings?


Indexing in Python strings allows you to access individual characters or substrings based on their position in the string.


The indexing starts at 0 instead of 1.


For example, `name[0]` will access the first character of the string `name`.


Q: How can I extract a specific segment from a string?


You can extract a specific segment from a string using slicing in Python.


Slicing involves using the colon (`:`) operator to specify the start and end positions of the substring you want to extract.


For example, `name[6:8]` will extract the substring from index 6 to 7 (excluding 8) from the string `name`.


Q: What is the purpose of the `center()` method?


The `center()` method is used to center-align a string within a specified width.


It takes an optional parameter for the width and another optional parameter for the fill character.


For example, `teststring.center(10)` will center-align the string `teststring` within a width of 10 characters.

Post a Comment

0 Comments