String in Python Programming Language
Strings in Python
String data-type in Python programming language is used to store the string values in a variable. The string is the only data type in python as a character in Java and C. In python characters are also treated as a string and are referred to as a string of length 1. The string is an immutable data type in python means we can’t append or remove item or element from the string variable
String data-type in Python Programming Language
Strings in the python programming language is a string data-type. We can perform many operations on String although strings are immutable we cannot append or remove elements from the string, but instead, we can initialize a new string and add elements to it. Strings are iterable and have indexes same as of array or list in python starting from 0. We can iterate strings in negative order starting with -1 as nth position and ending to -n + 1st position or at 0th index.
In-built functions in String
Python is a library rich language. For almost every operation you want to perform in python there are more chances that you might get a per-defined function for it. Some in-built functions for string data-type in the python programming language are:
- len()
- join()
- count()
- upper()
- lower()
- replace()
etc.
Important built-in functions
Function | Description |
---|---|
len() | Length of the string |
count() | Number of times a element is present in a string |
isalpha() | Returns true if the characters of the string are alphabetic |
isdigit() | Returns true if the characters of the string are digit. |
join() | Join the elements of strings at the end. |
lower() | Converts the string to lower case. |
upper() | Converts the string to upper case. |
replace() | Returns the string with replaced sub-part. |
Operations on Strings
Let’s discuss some operations on string by code:
#user input of string Var = input('Enter a string :') print(Var) #initialize an string String = 'PrepInsta' String1 = "PrepInsta" String2 = '''PrepInsta''' #print String print(String) print(String1) print(String2) #Length of String length = len(String) print(length) #slicing in String print(String[0:5]) print(String[:4]) print(String[2:]) print(String[-7:-2]) #printing reverse of string using slicing print(String[::-1]) #iterating through string using for loop for i in String: print(i,end=" ") print() #Concatenation of String print(String + String1) print(String[0:4] + 'shake')
Output: Enter a string :String String PrepInsta PrepInsta PrepInsta 9 PrepI Prep epInsta epIns atsnIperP P r e p I n s t a PrepInstaPrepInsta Prepshake
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment