What is Python String Slicing ?
Python String slicing is a method used to extract a portion of a string and creating a new string with the extracted part.
It's done by specifying a range of indices within square brackets following the string variable.
Slicing Syntax :-
string[start_index:end_index:step]
where
start_index:-
The index from which the slicing starts ( Included ).end_index:-
The index at which the slicing ends ( Excluded ).step (optional):-
The step value, specifying how many characters to skip. If not provided, it defaults to 1.
Slicing Examples :-
my_string = "Hello, World!" # Slice from index 1 to index 5 (exclusive) print(my_string[1:5]) # Output: "ello" # Slice from index 7 to the end print(my_string[7:]) # Output: "World!" # Slice from the beginning to index 5 (exclusive) print(my_string[:5]) # Output: "Hello" # Slice every other character print(my_string[::2]) # Output: "Hlo ol!" # Reverse the string print(my_string[::-1]) # Output: "!dlroW ,olleH"
What is Python String Concatenation?
String concatenation is the process of combining
multiple strings
into one.
In simpler terms, it's like gluing together pieces of text
to form a longer piece of text.
In Python, you can concatenate strings using the +
operator
Python String Concatenation Examples :-
first_name = "John" last_name = "Doe" full_name = first_name + " " + last_name print(full_name) # Output: "John Doe"
Python String concatenation is handy when you need to build dynamic strings,
such as constructing messages, forming file paths, or generating HTML/CSS code.
It's a fundamental operation in string manipulation and text processing tasks.