String in Python
Dec 23, 2023 by Ankit Srivastava
Categories
Enroll Now to Access Multiple Intensive Courses for Free
- So basically, strings are used to represent textual data. They are sequences of characters enclosed in single quotes (‘) or double quotes (“).
Initialising an empty string
- Initializing an empty string can be beneficial because it provides a placeholder for data to be added or modified later in the program.
String as arrays
Looping Through a String
Concatenation
- Combining two or more strings together using the + operator or the str.join() method.
- Let us try to cover the concept using an example.
Slicing
- String slicing in Python refers to the process of extracting a portion (substring) of a string by specifying a range of indices.
- Let us consider an example.
my_string = “SprintGrad”
substring_ = my_string[1:5] Python extracts a substring starting from the character at index 1 (‘p’) up to the character at index 5 (‘n’), excluding the character at index 5 , giving the output as “prin”.
String Formattting
- String formatting in Python refers to the process of creating formatted strings by inserting values or expressions into a template string.
- It allows us to construct dynamic strings by combining fixed text with variable data.
Using str.format() method:
Using f-strings (Formatted string literals):
Escape Character
- Escape characters in Python are special characters that are used to represent certain non-printable or special characters within string literals.
- They are denoted by a backslash (\) followed by a specific character or sequence.
- Here’s an explanation of escape characters with an example:
Other useful escape characters used in Python :
Getting the length of a string
- To get the length (number of characters) of a string in Python, you can use the len() function.
- The len() function returns the number of characters in a string, including spaces, punctuation marks, and special characters. Here’s an example for it.
Replication
- It replicates the string.
- In Python, you can replicate a string by using the multiplication operator ‘*’.
- Share:
No comments yet! You be the first to comment.