String in Python - 2

Sajjad Rahman - Aug 23 '23 - - Dev Community

Immutability of Strings

Strings are a fundamental data type in Python, serving as a sequence of characters. However, one key property of strings is their immutability. This means that once a string is created, its individual characters cannot be changed. Let's delve into this concept with an example:

name = "abir"
name[0] = 'p' # This will raise a TypeError

Running the above code snippet will result in an error: "TypeError: 'str' object does not support item assignment." This error demonstrates the immutability of strings, preventing direct modification of characters.
Replacing Characters in a String

While you can't modify characters in an existing string, you can create a new string with desired alterations. For instance, let's assume we have the string 'abir', and we want to replace the first character 'a' with 'k'. Here's how to accomplish it:

name = "abir"
last_letters = name[1:]
new_name = 'k' + last_letters
print(new_name)  # Output: "kbir"
Enter fullscreen mode Exit fullscreen mode

In this example, string slicing is used to extract characters without the first one. By concatenating the desired character ('k') with the sliced portion, the new string 'kbir' is formed.

String Multiplication

Python permits us to multiply strings to repeat them a specified number of times. For instance:

first_name = 'Jon'
multiplied_name = first_name * 10
print(multiplied_name)  # Output: "JonJonJonJonJonJonJonJonJonJon"
Enter fullscreen mode Exit fullscreen mode

Here, the string 'Jon' is multiplied by 10, leading to the repetition of the string 10 times.

Changing Case (Upper and Lower )

We can change the letters smaller to capital by use of upper(), and vice versa.

jon = " hello bangladesh mlops club"
upper_case_jon = jon.upper() 
print(upper_case_jon) # Output: " HELLO BANGLADESH MLOPS CLUB"
Enter fullscreen mode Exit fullscreen mode

Splitting Strings

The split() method divides the string into a list of words, like['hello', 'bangladesh', 'mlops', 'club'].

jon = " hello bangladesh mlops club"
split_jon = jon.split()
print(split_jon)  # Output: ['hello', 'bangladesh', 'mlops', 'club']
Enter fullscreen mode Exit fullscreen mode

The split() parameter is null which means when it finds the space then the split() words. We can pass a parameter inside the method like split('a') and then look at the example

jon = " hello bangladesh mlops club"
split_jon = jon.split('a')
print(split_jon)  # Output: [' hello b', 'ngl', 'desh mlops club']
Enter fullscreen mode Exit fullscreen mode

More Methods

Remove leading and trailing whitespace

sentence = " Python Programming is Amazing       "
cleaned_sentence = sentence.strip() 
print(cleaned_sentence) # Output: "Python Programming is Amazing"
Enter fullscreen mode Exit fullscreen mode

Count the occurrences of a substring

sentence = "Python Programming is Amazing"
count_amazing = sentence.count("Amazing") 
print(count_amazing) # Output: 1
Enter fullscreen mode Exit fullscreen mode

Check if the string starts with a certain substring

sentence = "Python Programming is Amazing"
starts_with_python = sentence.startswith("Python") 
print(starts_with_python) # Output: True

Enter fullscreen mode Exit fullscreen mode

Replace a substring with another substring

sentence = "Python Programming is Amazing"
new_sentence = sentence.replace("Amazing", "Incredible") 
print(new_sentence) # Output: " Python Programming is Incredible "
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this tutorial, we delved into the immutability of strings and explored various string methods that enable us to manipulate and process textual data effectively. By understanding the principles of string immutability and harnessing the power of string methods, you can create more dynamic and flexible programs for handling string-related tasks.

For more learn about string methods please go here python documentation
💡
Comment your thoughts

🐦 Twitter: @sajjadrahman56 🐦

🐙 GitHub: sajjadrahman56 🐙

🔗 LinkedIn: sajjadrahman56

Stay connected and follow me on my social media accounts to keep up with my latest updates and projects! 🌟 Let's collaborate and share knowledge. 🤝 Looking forward to engaging with you in the tech community! 👩‍💻👨‍💻

. . . . . . . . . . . . . . . .