Data types in Python - string

String

Exploring Strings in Python

A sequence of characters

In Python , a string is a sequence of characters enclosed in either single quotes ( ' ) or double quotes ( " ). Strings are versatile and widely used in programming to represent text-based data.

Creating Strings

To create a string, you can simply assign a sequence of characters to a variable . For example:

my_string = "Hello, world!"

In this example, we created a string with the content "Hello, world!" and assigned it to the variable my_string .

String Methods

The same as different data types , strings in Python come with a variety of built-in methods that allow us to manipulate and work with strings. Here are some commonly used string methods:

len()
Returns the length of the string.
lower()
Converts the string to lowercase.
upper()
Converts the string to uppercase.
strip()
Removes leading and trailing whitespace from the string.
split()
Splits the string into a list of substrings based on a specified delimiter.
replace()
Replaces occurrences of a substring with another substring.

Example

Let's see an example that demonstrates some of these string methods in action. We have a string that contains a sentence, and we want to manipulate it using the methods mentioned above:

sentence = " Python is Fun! "
length = len(sentence)
lowercase = sentence.lower()
uppercase = sentence.upper()
stripped = sentence.strip()
words = sentence.split()
replaced = sentence.replace("Python", "Programming")

After running this code, we can access the modified string values stored in the respective variables. For example:

print(length) # Outputs the length of the string
print(lowercase) # Outputs the string in lowercase
print(uppercase) # Outputs the string in uppercase
print(stripped) # Outputs the string with leading and trailing whitespace removed
print(words) # Outputs the list of words from the string
print(replaced) # Outputs the string with "Python" replaced by "Programming"

By utilizing these string methods, we can perform various operations and transformations on strings to suit our needs.

Now you can manipulate and modify strings

Strings are an essential part of Python programming. They allow us to work with text-based data and perform various operations on it. By understanding the basics of creating strings and utilizing string methods, you can manipulate and modify strings to accomplish different tasks. Continue exploring and experimenting with strings to enhance your programming skills!