Hello guys, Let’s learn something new in Python. In this module, we will be learning What is Python Strings. Today we will be learning one of the most required and important topics which are very useful and helps you to work with string in Python. So let’s start.
What are Python Strings?
A string in Python is a word, line, or statement written inside a ”(single quote) or “”(double quotes). Python Strings store character type values. Strings are immutable once defined and can not be altered. If you try to update the string then it will create an error.
‘hello’ is a string and it is treated the same as “hello” both are the same in terms of Python.
We can print or display strings by using the print command as
print("hello") // It will display hello on the screen.
Assigning a string to a variable
If you want to assign a string to a variable or store a value. It can be done with the variable name followed by the equal operator(=) and then the string.
a="Hello" print(a)// It will print Hello on the screen.
We can store the multiline strings in a variable by using three single quotes or three double quotes.
A= '''Ram is a good boy, He plays cricket, He dances very well.''' print(A) //it will print the multiline input on the screen.
String As Array
In Python, Strings are treated as an array of bytes representing Unicode. A bit stores a character and the whole string gets stored like this. We can access a character by specifying a variable with a location in the square bracket for which we have to fetch.
A="Programming" print(A) //it will print g because in python the first character has 0 positions.
Loop Through String
Strings are treated as arrays so we can loop through strings as well.
A="python" for x in A: print(x) //it will print the whole string at the end of the loop.
String Methods In Python
It will convert the first character to upper case, and the rest to lower case.
Text= python is GREAT! x=Text.capitalize() Print(x) Output: Python is great!
It will return the count or number of times a specified value appears in the string.
Text=python is great, python is fun. X=Text.count("python") Print(x) Output: 2
In this we can add the start and end positions with value then it will count in between the specified position. Like Text.count(“python”,9,22)then it will return only 1.
It will search the string for a specified value and return the position where it was found.
text = "Hello, welcome to my world." x = text.find("welcome") print(x) output:7
index() method finds the 1st occurrence of the specified value. If not found raises an exception we can pass start and end parameters which are optional if not then it will find in the whole string.
text = "Hello, welcome to my world." x = text.find("e",5,10) print(x) output:8
It returns True if all characters in the string are alphanumeric i.e alphabets(a-z) and numbers (0-9).
Text="Abcd 10" x = txt.isalnum() print(x) Output: False //as string contains space.
It returns True if all characters in the string are alphabet.
text = "Company" x = text.isalpha() print(x) Output: True //As string only contains alphabet.
It returns true if all characters are in lowercase in a string.
text = "company" x = text.isalpha() print(x) Output: True
The join() method takes all items in an iterable and joins them into one string.
mytuple =("Jack", "Jill", "John") x=" ".join(mytuple) print(x) Output: Jack Jill John
It converts a string into lowercase.
text= "Python IS LOVE" x = text.lower() print(x) Output: python is love
This method removes any leading space or character as specified in the parameters.
text= " python" x=text.lstrip() print(x) Output: Python //removes all the space on left.
This method replaces a specified phrase with another specified phrase. It replaces all the occurrences of specified phrases if nothing is specified.
text = "I like bananas" x = text.replace("bananas", "apples") print(x) Output: I like apples.
This method removes any trailing space or character as specified in the parameters.
text= "python " x=text.rstrip() print(x) Output: Python //removes all the space in right.
splits a string at the specified separator and returns a list.
text = "I like python" x = text.split() print(x) Output: ["I", "like", "python"]
Remove space from the beginning and end of the string.
text= " python " x= text.strip() print(x) output: python
converts the string in upper case.
text= "i like python" x=text.upper() print(x) Output: I LIKE PYTHON
Write the Program to replace a string in the middle of a string in Python
def middle_replace(txt): li = list(txt.split(" ")) #convert the string to list char= li[(len(li)-1) //2:(len(li)+2)//2] #find middle word from string list_to_string= ",".join(char) #convert list to string new_string = txt.replace(list_to_string, "word") #replace middle word to give word return new_string word=input() #take input to replace middle_char("python is cool")
Convert Integer to String
To convert any integer into a string pass it in str() and it will convert its data type to a string.
num = 10 print(type(num)) # check and print type of num variable converted_num = str(num) # convert the num into string print(type(converted_num)) # check and print type converted_num variable
How to store a long multiline String in Python
We generally initialize a variable with a specific string.
text= “I like Python. Python is an interpreted language.”
This is a single-line initialization of a string.
If you want to store the multiline string in a variable you have to use ”’ multiline string ”’ or “““ multiline string”””
text = “““Python is fun. I like python. Python is love”””
#this will store all lines in text.
I hope this may help you to know more about strings in Python. For better understanding please try it out and see our other blogs. Happy learning.