Introduction

Setup

Operators

variable

String

Number

Dtype & Comment

Lists

Tuples

Sets

Dictionaries

if else statement

For Loop

While Loop

iterator & iterable

Pre-Built functions

Function

Decorators

generators

Types of errors

Exceptions Handling

OOP

Regular expression

Create module

OS module

Date module

Random module

Math

Statistics module

Exercise 1

Exercise 2

Exercise 3

Learn Data Structure & Algorithm

Learn Numpy

Learn Pandas

Learn Matplotlib

Learn Seaborn

Learn Statistics

Learn Math

Learn MATLAB

Learn Machine learning

Learn Github

Learn OpenCV

Learn Deep Learning

Learn MySQL

Learn MongoDB

Learn Web scraping

Learn Excel

Learn Power BI

Learn Tableau

Learn Docker

Learn Hadoop

Python string

What is string?

A string is similar to text. Text is a string and you can also write a number as a string but when you write a number as a string then the number behaves Like a text. Then you can't perform any mathematical operation on it. You can also write code as a string but if you write code as string then code will become a text. To create a string, write that thing which you want to make or see as a string in the double or single quotation. If you write anything in a single or double quotation then it will work as a string.

Example:
Input
x="RafsunAhmad"
y='45'
print(x)
print(y)
Print("RafsunAhmad") Output
45
RafsunAhmad

How to convert number into string?

To convert anything into a string use the str() function.

Example:
Input
x=5
y=str(5)
print(type(x))
print(type(y))
Output
< class "int">
<class "str">

Python string slicing

By using slicing, you can return a range of characters. For slicing, you have to specify the start index and the end index and between the start and end index use the colon symbol. After this, you will get a part of the string. A negative index means to start the slice from the end of the string.

What is index?

An index is nothing but the position number of characters. Position or index number starts from zero. For example, we have the word RafsanAhmad.Here R alphabet index number is 0 and the alphabet A index number is 6.
Remember one thing, starting number means, start according to the given index number from a word.
Suppose if we wrote 5 then the slicing will start from the number 5 character present in a word. It means the output will have the character present in the number 5 position in the word. End index means slicing will stop at the given index number.
Suppose we wrote the end index value is 9, then the slicing will stop at the 9th index number characters. So we can say that we will get characters from starting index to the end index.

Example:1
Input
b = "RafsunAhmad"
print(b[2:9])
Output
fsunAhma

Here we will get letters from the 7th index to the 15th index. Here 7 means from 7 characters of RafsunAhmad slicing will start and 15 means this slicing will happen till the previous index of 15 characters.

Example:2
Input
b = "Rafsun,Ahmad"
print(b[:6])
Output
Rafsun

In example 2 we will get all the characters from 0 indexes to 6 indexes. If we don't pass stating index value and just write end index value then the slicing will start from 0 indexes and will continue till end index.

Example:3
Input
b = "Rafsun,Ahmad"
print(b[5:])
Output
n,Ahmad

Here we will get all the characters from the 5 index to the last index. If you don't pass the end index value and just pass starting index value then the slicing will start from starting index and slicing will happen till the last index.

Example:4
Input
b = "RafsunAhmad"
print(b[-9:-7])
Output
fs

Here you will get a -7 index to -15 index value. Here the slicing will start in the reverse direction(d to R)

How to concatenate string?

In python to concatenate multiple strings, the + operator is used.

Example:1
Input
b = "Rafsun"
c = "Ahmad"
print(b+c)
Output
RafsunAhmad
Example:2
Input
b = "Rafsun"
c = "Ahmad"
print(b+" "+c)
Output
Rafsun Ahmad
To give space this " " is used

Escape characters

A lot of work can be performed using escape characters like \n(for newline), etc.

List of some escape characters

Name Code Use
Tab \t Use to give space
New Line \n Use to create newline
Backslash \\ Use to insert a single quotation
Single Quote \' Use to insert one \ (backslash).

Example:
Input
b = "Rafsun\nAhmad"
print(b)
Output
Rafsun
Ahmad

upper() function

The upper function is used to convert letters into upper cases.

Example:
Input
b = "RafsunAhmad"
print(b.upper())
Output
RAFSUNAHMAD

lower() function

The lower function is used to convert letters into lower case.

Example:
Input
b = "RafsunAhmad"
print(b.lower())
Output
rafsunahmad

capitalize() function

capitalize function is used to convert the first letter of a sentence into upper case.

Example:
Input
b = "i love to eat mango and mango is very yummy."
z=b.capitalize()
print(z)
Output
I love to eat mango and mango is very yummy.

endswith() function

endswith function returns true if the sentence ends with the given or specified value. If not then return false.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.endswith("fruit.")
print(x)
Output
True

find() function

find() function finds the given or specified value in the sentence and returns the index number. This method will find the first occurrence of that specified value. If the find function can't find anything then it will return -1.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.find("fruit")
v= b.find("fruit",1,20)
print(x)
print(v)
Output
37
-1

In the v variable of the find function, we wrote 1 and 20. It means that the find function will find that specified thing between 1 index to 20 indexes. We will see that between 1 to 20 index of the sentence there is no word fruit so the output is -1.

isalnum() function

isalnum() function returns true if all characters in the string are alphanumeric. If not then return false.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.isalnum()
print(x)
Output
False

isalpha() function

isalpha() function return true if all characters in the string are alphabet.If not then return false.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.isalpha()
print(x)
Output
False

len() function

This function prints the length of a string.

Example:
Input
v="SelfTaught"
z="Apple is a very good fruit"
print(len(v))
print(len(z))
Output
9
26

isdecimal() function

isdecimal() function returns true if all characters in the string are decimals. If not then return false.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.isdecimal()
print(x)

isdigit() function

isdigit() function returns true if all characters in the string are digit. If not then return false.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.isdigit()
print(x)
Output
False

isidentifier() function

isidentifier() function return true if all characters in the string is an identifier.If not then return false.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.isidentifier()
print(x)
Output
False

islower() function

islower() function returns true if all characters in the string are lower case. If not then return false.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.islower()
print(x)
Output
False

isnumeric() function

isnumeric() function return true if all characters in the string are numeric. If not then return false.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.isnumeric()
print(x)
Output
False

istitle() function

istitle() function returns true if all characters in the string are titled. If not then return false.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.istitle()
print(x)
Output
False

isupper() function

isupper() function return true if all characters in the string are upper case. If not then return false.

Example:
Input
b = "I love mango, mango are my favorite fruit."
x = b.isupper()
print(x)
Output
False

join() function

join() function convert tuple,dictionary,list etc into one string.Here we separate the words using a separator.

Example:
Input
mylist = ["name","Rafsun", "country", "USA"]
mySeparator = "**"
x = mySeparator.join(mylist)
print(x)
Output
name**Rafsun**country**USA

strip() function

strip() function remove the space from the left and right side of a string. lstrip remove the space of the left side and rstrip remove the space of the right side.

Example:
Input
v =" Rafsun Ahmad USA "
x = v.lstrip()
y = v.rstrip()
z = v.strip()
print(x)
print(y)
print(z)
Output
Rafsun Ahmad USA
    Rafsun Ahmad USA
Rafsun Ahmad USA

splitlines() function

splitlines() function split string from line breaks and create a list.

Example:
Input
b = "Thank you for using SelfTaught\nCome back soon"
x = b.splitlines()
print(x)
Output
['Thank you for using SelfTaught', 'Come back soon']

startswith() function

startswith() function return true if the string starts with that specified value and if not then returns false.

Example:
Input
b = "Thank you for using SelfTaught\nCome back soon"
x = b.startswith("Thank")
print(x)
Output
True

swapcase() function

swapcase() function swap uppercase word to lowercase and lower case word to upper case.

Input
txt = "heLlO my NaMe iS rAFSUN"
x = txt.swapcase()
print(x)
Output
HElLo MY nAmE Is Rafsun

title() function

title() function converts each word's first letter into upper case.

Example:
Input
b = "Thank you for using SelfTaught and Come back soon"
x = b.title()
print(x)
Output
Thank You For Using SelfTaught And Come Back Soon

count() function

count() function returns the number of times the given value appears in the string.

Example:
Input
b = "I love to eat mango and mango is very yummy."
v=b.count("mango")
z=b.count("mango",1,20)
print(v)
print(z)
Output
2
1

In the z variable of the count function, you write 1 and 20. It means that the count function will find how many times mango appears between 1 index to 20 indexes.

replace() function

replace() function used to replace string value with another string value. In the function bracket first value is for that word or symbol that you want to replace and the second value is the word that you want to replace with.

Example:
Input
b = "RafsunAhmad"
print(b.replace("A","a"))
Output
Rafsunahmad

split() function

In the split function, a separator is used to separate. The default separator is space but you can use different separators according to your need like comma, colon, quotation, slash, etc. The split function separates numbers or strings by the given separator and returns all distinct values as a list.

Example:
Input
b = "Rafsun,Ahmad"
c = "Rafsun/Ahmad"
d = "Rafsun Ahmad"
print(b.split(","))
print(c.split("/"))
print(d.split())
Output
["Rafsun","Ahmad"]
["Rafsun","Ahmad"]
["Rafsun","Ahmad"]

String formatting

Without String formatting

Example:
Input
Name =input("Enter your name:")
age=int(input("Enter your age:"))
print("Hello" + Name + ".Your age is" + age)
Output
Enter your name:Rafsun
Enter your age:21
Hello Rafsun.Your age is 21

With string formatting

Example:
Input
Name =input("Enter your name:")
age=int(input("Enter your age:"))
print(f"Hello {Name}.Your age is {age}")
print(f"Hello {Name}.Your age is {age+2}")
Output
Enter your name:Rafsun
Enter your age:21
Hello Rafsun.Your age is 21
Hello Rafsun.Your age is 23

CodersAim is created for learning and training a self learner to become a professional from beginner. While using CodersAim, you agree to have read and accepted our terms of use, privacy policy, Contact Us

© Copyright All rights reserved www.CodersAim.com. Developed by CodersAim.