String Definition in Python
A python string is a collection of characters. It is created using single quotes ('jiocoding')or double quotes ("jiocoding") and triple quotes('''jiocoding'''). We can print string using print() function. We can also print particular character of string using index number.
String are stored in the form of array sequence of characters used to store and manipulate text data. It is a data type that represents textual data. Strings in python are immutable meaning that once a string is created you cannot modify contents.
In python strings are objects which means they have methods that can be called to perform various operations.
How to Create String in Python
s1='Welcome To Jiocoding Website'
s2="Welcome To Python Language"
s3='''You can learn python Basic To Advanced'''
print(s1)
print(s1)
print(s1)
print(type(s1))
print(type(s2))
print(type(s3))
============OUTPUT============
Welcome To Jiocoding Website
Welcome To Python Language
You can learn python Basic To Advanced
<class 'str'>
<class 'str'>
<class 'str'>
String All Method or Functions in Python
| Len Function: A length function can be used to get the length of string character. |
| Capitalize Function: A capitalize function can be used converts the first letter of the string into uppercase. |
| Casefold Function: A casefold function can be used converts string into lowercase. |
| Center Function: Center function can be used to align the string to the center. |
| Endswith Function: Endswith function returns are boolean value True or False. It the given string ends with specified string returns true otherwise false. |
| Startswith Function: Startwith function returns boolean value True or False. It the given string starts with specified string returns true otherwise false. |
| Find Function: It is used to search the specified string in a string. If the specified string is found then it returns the position of where it is found. |
| Index Function: This method is same as find but it raises an error when the specified string is not found. |
| Format Function: It is used to format the string. We can insert specified value inside the string using format () method. The specified value is inserted inside string using placeholder. The placeholder is identified using numbered indexes {0} or empty placeholders{} |
| Isalnum Function: It is used to check specified string is alphanumeric or not. String that contains only alphabet and number is called alphanumeric. It returns boolean value True or False. |
| Isalpha Function: It is used to check specified string is alphabetic or not. It returns boolean value True or False. It returns true if string is alphabetic otherwise returns false. |
| isdecimal Function: It is used to check all the characters of string are decimal or not. It returns boolean value True or False. It returns true if all characters are decimal otherwise returns false. |
| Isdigit Function: It is used to check all the characters of string are digit or not. It returns boolean value True or False. It returns true if all characters are digit otherwise returns false. |
| Isidentifier Function: It returns true if the specified string is valid identifier otherwise returns false. |
| Islower Function: It returns true if all the characters of the string is in lowercase otherwise returns false. |
| Isnumeric Function: It returns true if all the characters of the string are numeric character otherwise returns false. |
| Isupper Function: It returns true if all the characters are in uppercase otherwise returns false. |
| Isspace Function: It returns true if all the characters are white space otherwise returns false. |
| Lower Function: It is used to convert all the characters of a string to Lower case. |
| Upper Function: It is used to convert all the characters of a string to Upper case. |
| Swapcase Function: It converts lowercase characters into uppercase and uppercase characters into lowercase. |
| Strip Function: It removes unwanted white-space from string. |
| Istrip Function: It removes left side unwanted white-space from string. |
| Rstrip Function: It removes right side unwanted white-space from string. |
| Replace Function: It replaces the old string with new string. |
| Split Function: It is used to break the sentence into words using separator. The default separator is white space. split() function returns list. |
Escape sequences Character in Python
A escape sequences character can be used to define special characters within strings. Escape sequences character allow strings to be formatted.
An escape sequence is a collection of characters the first of which is the backslash (\). Like that (\n) is an escape sequence that represents a new line.
| Escape Sequence | Description |
|---|---|
| \\ | Backslash(\) |
| \' | Single Quote(') |
| \" | Double Quote(") |
| \a | Beep |
How to Use String Escape in python
data1="Welcome \\To Jiocoding Website"
data2="Welcome \tTo Jiocoding Website"
data3="Welcome \" Jiocoding Website"
data4="Welcome \a Jiocoding Website"
print(data1)
print(data2)
print(data3)
print(data4)
============OUTPUT============
Welcome \To Jiocoding Website
Welcome To Jiocoding Website
Welcome " Jiocoding Website
Welcome Jiocoding WebsitePython String Indexing and Slicing
A python string indexing allows you to access individual characters of a string using their positions. Python indexing is starting of first character in zero- based meaning the first character of a string has index 0 and second character index 1 and so on. Python string supports negative index which allows you to access characters of a string from the end. We can print string using print() function. We can also print particular character of string using index number. String are stored in the form of array.
Example of Index Slicing
s="Jiocoding"
print(s[0])
print(s[1])
print(s[2])
print(s[3])
print(s[4])
print(s[5])
print(s[6])
print(s[7])
print(s[8])
============OUTPUT============
J
i
o
c
o
d
i
n
gPython String Slicing Methods
The python slicing is allows you to extract substrings from a string using a range of character. We can access range of characters from string using slicing operator colon(:).
Example of String Slicing in Python
s="Welcome To Jiocoding Website"
print("String:",s)
print("string[2:6]:",s[2:6])
print("string[7:-1]:",s[7:-1])
print("Negative Index:",s[-1])
============OUTPUT============
String: Welcome To Jiocoding Website
string[2:6]: lcom
string[7:-1]: To Jiocoding Websit
Negative Index: eF String Meaning in Python
A F-strings is most important features of python were introduced in Python 3.6 and provide a convenient way to format strings. They can allow to the variable embedded directly into string. To create an f-string precede the string F or f and then include variable enclosed in curly braces which will be replaced by their values when the program is executed.
Example of F String in Python
data="String"
name="Jiocoding"
link="https://www.jiocoding.com"
print(f "Python Topic:{data} or Website Name is:{name} and Website Link:{link}")
============OUTPUT============
Python Topic:String or Website Name is:Jiocoding and Website Link:https://www.jiocoding.comPython String Format Escape Curly Braces
A string format() method in python allows you to format strings using positional arguments. These are the curly braces placeholders that can be replaced with values from the arguments passed to the method. The format() method also provides many options for customizing formatting.
Example of String Format Method
data="String"
name="Jiocoding"
s[0]="J"
link="https://www.jiocoding.com"
print("Python Topic:{0} or Website Name is:{1} and Website Link:{2}".format(data,name,link))
============OUTPUT============
Python Topic:String or Website Name is:Jiocoding and Website Link:https://www.jiocoding.comConverting Characters to Bytes Python
A converting strings to bytes and back is a key operation when working with text data and network communications in Python.
- Encoding with the encode() function converts data from a character string to a sequence of bytes.
- Decoding with the decode() function converts bytes back to human readable characters.
- Strings display text in human readable format while bytes store characters as binary data.
We have a string variable consisting of ASCII characters. ASCII is a subset of the Unicode character set. The encode() method is used to convert it to a byte object. The decode() method converts a byte object back to a str object. The encoding method used is utf-8.
Example of Byte Pair Encoding
name="Jiocoding"
byte_data=name.encode('utf-8')
print("String To Byte Code:",byte_data)
print(type(byte_data))
byte_data.decode('utf-8')
print("String To Byte Code:",name)
print(type(byte_data))
============OUTPUT============
String To Byte Code: b'Jiocoding'
<class 'bytes'>
String To Byte Code: Jiocoding
<class 'str'>Python Raw Format String
A string is called a raw string if it has an r or R prefix before the quote characters.
Under normal circumstances, there is no difference between the two. A raw string does not process escape sequences if they are present in the string.
When a normal string is printed the escape character \n is processed to add a newline because of the raw string operator r the effect of the escape character or print escape character.
Example of Raw Escape Function in Python
s="Welcome To\nJiocoding Website"
print("Normal String:",s)
raw_data=r"Welcome To\nJiocoding Website"
print("Raw String Data:",raw_data)
============OUTPUT============
Normal String: Welcome To
Jiocoding Website
Raw String Data: Welcome To\nJiocoding WebsiteString Concatenation in Python
A string concatenate can be used to operation of combining two or more strings. The result of this operation is a new string containing the original strings. There are two operators can be used to concatenate strings.
Explain String Concatenation with Example in Python
s1="Hello Python Programmer"
s2=" "
s3="Welcome to Jiocoding"
print(s1+s2+s3)
============OUTPUT============
Hello Python Programmer Welcome to Jiocoding
Update String in Python
How to Update String in Python Method 1
s="Welcome To Jiocoding Website"
print("Before Update String:",s)
s="Jiocoding"
print("After Update String:",s)
============OUTPUT============
Before Update String: Welcome To Jiocoding Website
After Update String: JiocodingHow to Update String in Python Method 2
s="Welcome To Jiocoding Website"
print("Before Update String:",s)
s[0]="J"
print("After Update String:",s)
============OUTPUT============
Before Update String: Welcome To Jiocoding Website
TypeError: 'str' object does not support item assignmentString Repeating Value in Python
How to Use asterisk Symbol in Python
s="Jiocoding "
print(s*5)
============OUTPUT============
Jiocoding Jiocoding Jiocoding Jiocoding Jiocoding
All String Functions in Python with Examples
Python Capitalize Function
A capitalize function converts the first letter of the string into uppercase.
s="jiocoding website"
print("Before String:",s)
print("After String:",s.capitalize())
============OUTPUT============
Before String: jiocoding website
After String: Jiocoding website
Python Casefold Function
A casefold function can be used converts all upper character in string into lowercase.
s="Jiocoding Website"
print("Before String:",s)
print("After String:",s.casefold())
============OUTPUT============
Before String: Jiocoding Website
After String: jiocoding website
Python Center Function
Center function can be used to align the string to the center. It has two parameters width and fill character fill character is optional.
s="Jiocoding"
print("Before String:",s)
print("After String:",s.center(20))
============OUTPUT============
Before String: Jiocoding
After String: Jiocoding
s="Jiocoding"
print("Before String:",s)
print("After String:",s.center(20,"$"))
============OUTPUT============
Before String: Jiocoding
After String: $$$$$Jiocoding$$$$$$
Python Endswith Function
A Endswith function can be used to returns boolean value True or False. It the given string ends with specified string value returns true otherwise returns false.
s="Jiocoding Website"
print(s.endswith("website"))
print(s.endswith("Website"))
============OUTPUT============
False
True
Python Startswith Function
A startswith function can be used to returns boolean value True False. It the given string starts with specified string value returns true otherwise returns false.
s="Jiocoding Website"
print(s.startswith("jiocoding"))
print(s.startswith("Jiocoding"))
============OUTPUT============
False
True
Python Find Function
A find function is used to search the specified string in a string. If the specified string is found then it returns the starting position. If the string is not find than return (-1).
s="Welcome To Jiocoding Website"
print("Position at:",s.find("Jiocoding"))
print("Not Found String:",s.find("Python"))
============OUTPUT============
Position at: 11
Not Found String: -1
Python index Function
A Index function is the same as find. If the given string is find than return position of string. but string are not find than raises an error when the specified string is not found.
s="Welcome To Jiocoding Website"
print("Position at:",s.index("Jiocoding"))
print("Not Found String:",s.index("Python"))
============OUTPUT============
Position at: 11
File "<main.py>", line 3, in <module>
ValueError: substring not found
Python format Function
Python format function can be used to format the string. We can insert specified value inside the string using format method. The specified value is inserted inside string using placeholder.
The placeholder is identified using numbered indexes {0} or empty placeholders{}.
name="Jiocoding"
address="Noida"
print("Website Name is:{0} Address is:{1}". format(name,address))
============OUTPUT============
Website Name is:Jiocoding Address is:NoidaPython isalnum Function
A isalnum function can be used to check specified string is alphanumeric or not. String that contains only alphabet and number is called alphanumeric. It returns boolean value True or False.
s1="jiocoding1234"
s2="jiocoding@1234"
print(s1.isalnum())
print(s2.isalnum())
============OUTPUT============
True
False
Python isalpha Function
A isalpha function can be used to check specified string is alphabetic or not. It returns boolean value True or False. It returns true if string is alphabetic otherwise returns false.
s1="jiocoding1234"
s2="jiocoding@1234"
print(s1.isalpha())
print(s2.isalpha())
============OUTPUT============
True
False
Python isdecimal Function
A isdecimal function can be used to check all the characters of string are decimal or not. It returns boolean value True or False. It returns true if all characters are decimal otherwise returns false.
s1="jiocoding"
s2="123456"
print(s1.isdecimal())
print(s2.isdecimal())
============OUTPUT============
False
True
Python isdigit Function
A isdigit function can be used to check all the characters of string are digit or not. It returns boolean value True or False. It returns true if all characters are digit otherwise returns false.
s1="jiocoding"
s2="123456"
print(s1.isdigit())
print(s2.isdigit())
============OUTPUT============
False
True
Python isidentifier Function
A isidentifier function is returns true if the specified string is valid identifier otherwise returns false.
s1="jiocoding"
s2="123456"
s3="jiocoding123"
s4="*jiocoding"
s5="ab@cdef"
print(s1.isidentifier())
print(s2.isidentifier())
print(s3.isidentifier())
print(s4.isidentifier())
print(s5.isidentifier())
============OUTPUT============
True
False
True
False
False
Python islower Function
A islower function is returns true if all the characters of the string is in lowercase otherwise returns false.
s1="jiocoding"
s2="Jiocoding"
print(s1.islower())
print(s2.islower())
============OUTPUT============
True
False
Python isnumeric Function
A isnumeric function is returns true if all the characters of the string are numeric character otherwise returns false.
s1="Jiocoding"
s2="12345"
print(s1.isnumeric())
print(s2.isnumeric())
============OUTPUT============
False
TruePython isupper Function
A isupper function is returns true if all the characters are in uppercase otherwise returns false.
s1="jiocoding"
s2="JIOCODING"
print(s1.isupper())
print(s2.isupper())
============OUTPUT============
False
TruePython isspace Function
A isspace function is returns true if all the characters are white space otherwise returns false.
s1=" "
s2="Jiocoding"
print(s1.isspace())
print(s2.isspace())
============OUTPUT============
True
FalsePython lower Function
A lower function can be used to convert all the characters of a string to Lower case.
s1="JIOCODING"
s2="Jiocoding"
print("s1:",s1.lower())
print("s2:",s2.lower())
============OUTPUT============
s1: jiocoding
s2: jiocodingPython upper Function
A upper function can be used to convert all the characters of a string to Upper case.
s1="jiocoding"
print("s1:",s1.upper())
============OUTPUT============
s1: JIOCODINGPython swapcase Function
A python swapcase function can be used to converts lowercase characters into uppercase and uppercase characters into lowercase.
s1="Jiocoding"
s2="JioCodinG"
print("string1:",s1.swapcase())
print("string2:",s2.swapcase())
============OUTPUT============
string1: jIOCODING
string2: jIOcODINgPython strip Function
A python strip function can be used to removes unwanted white-space from the string.
s=" Python "
print("Without strip:",s,"Programming")
print("With strip:",s.strip(),"Programming")
============OUTPUT============
Without strip: Python Programming
With strip: Python ProgrammingPython lstrip Function
A python lstrip function can be used to removes left side unwanted white-space from string.
s=" Python "
print("Without lstrip:",s,"Programming")
print("With lstrip:",s.lstrip(),"Programming")
============OUTPUT============
Without lstrip: Python Programming
With lstrip: Python ProgrammingPython rstrip Function
A python rstrip function can be used to removes right side unwanted white-space from string.
s=" Python "
print("Without rtrip:",s,"Programming")
print("With strip:",s.rstrip(),"Programming")
============OUTPUT============
Without rstrip: Python Programming
With rstrip: Python ProgrammingPython replace Function
A python replace function can be used to replaces the old string with new string.
s="Welcome To Python Language"
print("Original String:",s)
s=s.replace("Python","Jiocoding")
print("New String:",s)
============OUTPUT============
Original String: Welcome To Python Language
New String: Welcome To Jiocoding LanguagePython split Function
A python split function can be used to break the sentence into words using separator. The default separator is white space. split() function returns list.
s="Welcome To Jiocoding Website"
print("Original String:",s)
data=s.split();
print("New String:",data)
============OUTPUT============
Original String: Welcome To Jiocoding Website
New String: ['Welcome', 'To', 'Jiocoding', 'Website']
