Exploring the Power of Strings: A Comprehensive Guide to String Manipulation in Python
String in Python is a collection of characters enclosed inside quotation marks. It is a built-in data type in C. Unlike C programming language, Python has no character data type. SO, both character and words can be denoted by this data type.
Initializing String Variable
str1="Hello world !!!"
print(type(string)) # class <str>
Here, string names str1 is initialized with value of Hello world !!! and its type is printed.
Type Conversion To String Type
int1=95
float1=25.65
str1= str(int1)
str2= str(float2)
print(str1,str2) # 95 25.65
print(type(str1)) # <class 'str'>
Here, values of type int and float are converted to string using str() object. The value remains the same, but the type gets changed to string.
Accessing Elements Of String
greeting= "Hello User"
print(greeting[0]) # H
print(greeting[6]) # U
greeting[4]='i' # TypeError: 'str' object does not support item assignment
greeting='Good day'
print(greeting) # Good day
It is possible to access the value of the string using an index value which ranges from 0 to (length of string-1) but it is not possible for the character of the string to be changed. However, we change totally modify the whole string.
Functions Of String
Here are few methods that can be performed on string data type:
1. str (object)
Convert the object to string if possible.
num = 42
num_str = str(num)
2. len (string)
Convert the integer value of length of the given string. For example: If the string has 6 characters, it returns 6 as output.
greet="Hello"
print(len(greet)) # 5
3. format (string, *args, **kwargs)
Formats a string by replacing placeholders with values.
age=26
name="Henry"
text="My name is {} and I am {} years old.".format(name,age)
print(text) # My name is Henry and I am 26 years old.
4. split(string, separator)
:
Splits a string into substring when the separator appears and returns a list of substrings.
sentence = "Hello, world!"
words = sentence.split(", ")
print(words) # ['Hello', 'world!']
5. join (iterable)
:
Concatenates elements of an iterable (e.g., a list) into a single string using a specified separator. Works inverse of split () method.
words = ["Hello", "world!"]
sentence = ", ".join(words)
print(sentence) # Hello, world!
6. strip (string,character)
:
Removes leading and trailing characters (by default, whitespace) from a string.
text = " Hello, World! "
stripped_text = text.strip()
7. lower()
:
Converts a string to lowercase.
text = "Hello, World!"
lowercase_text = text.lower()
print(lowercase_text) # hello, world!
8. upper()
:
Converts a string to uppercase.
text = "Hello, World!"
uppercase_text = text.upper()
print(uppercase_text) # HELLO, WORLD!
This way, we can handle string in Python and manipulate them as we want.