Python Strings

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.

Python Strings

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.

For eg:
‘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 string 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.

Multiline String

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.

For eg:

A="Programming"
print(A[3]) 
//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.

For eg:

A="python"
for x in A:
print(x) //it will print the whole string at the end of the loop.

String Methods In Python

1. capitalize():

It will convert the first character to upper case, and the rest to lower case.

For eg:

Text= python is GREAT!
x=Text.capitalize()
Print(x)
Output: Python is great!

2. count():

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.

3. find():

It will search the string for a specified value and return the position where it was found.

For eg:

text = "Hello, welcome to my world."
x = text.find("welcome")
print(x)
output:7

4. index():

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.

For eg:

text = "Hello, welcome to my world."
x = text.find("e",5,10)
print(x)
output:8

5. isalnum():

It returns True if all characters in the string are alphanumeric i.e alphabets(a-z) and numbers (0-9).

For eg:

Text="Abcd 10"
x = txt.isalnum()
print(x)
Output: False //as string contains space.

6. isalpha():

It returns True if all characters in the string are alphabet.

For eg:

text = "Company"
x = text.isalpha()
print(x)
Output: True //As string only contains alphabet.

7. islower():

It returns true if all characters are in lowercase in a string.

For eg:

text = "company"
x = text.isalpha()
print(x)
Output: True

8. join():

The join() method takes all items in an iterable and joins them into one string.

For eg:

mytuple =("Jack", "Jill", "John")
x=" ".join(mytuple)
print(x)
Output: Jack Jill John

9. lower():

It converts a string into lowercase.

For eg:

text= "Python IS LOVE"
x = text.lower()
print(x)
Output: python is love

10. lstrip():

This method removes any leading space or character as specified in the parameters.

For eg:

text= " python"
x=text.lstrip()
print(x)
Output: Python //removes all the space on left.

11. replace():

This method replaces a specified phrase with another specified phrase. It replaces all the occurrences of specified phrases if nothing is specified.

For eg:

text = "I like bananas"
x = text.replace("bananas", "apples")
print(x)
Output: I like apples.

12. rstrip():

This method removes any trailing space or character as specified in the parameters.

For eg:

text= "python "
x=text.rstrip()
print(x)
Output: Python //removes all the space in right.

13. split():

splits a string at the specified separator and returns a list.

text = "I like python"
x = text.split()
print(x)
Output: ["I", "like", "python"]

14. strip():

Remove space from the beginning and end of the string.

text= " python "
x= text.strip()
print(x)
output: python

15. upper():

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”””

For eg:

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.