0% completed
Strings in Python are sequences of characters and are among the most widely used data types.
Strings are immutable, which means that once a string is created, its characters cannot be modified directly. This property ensures that strings can be passed around safely in a program without altering the original data. Python treats single characters as strings of length one, making it consistent in handling textual data. Various operations such as slicing, concatenating, and formatting are available, allowing for robust manipulation of text data.
Strings in Python can be created using single quotes
, double quotes
, or triple quotes
for multiline strings. This flexibility allows for easy handling of text data in various scenarios:
In the following example, we will define strings using different types of quotes and print them:
Explanation:
String indexing in Python is a powerful feature that allows you to access individual characters in a string. Python supports both positive
and negative
indexing.
0
for the first character, 1
for the second, and so on.-1
for the last character, -2
for the second-last, and continues similarly towards the start of the string.Here, we demonstrate how to access characters from a given string using both positive and negative indexing, and we'll print the outputs to illustrate:
Explanation:
'p'
in "Python programming is fun!"
.'f'
in the same string.'P'
, the very first character, demonstrating positive indexing starting at zero.'!'
, the last character, showcasing negative indexing starting from the end.In the next lesson, we will learn to use stirng operators.
.....
.....
.....