Home » Posts tagged 'Python strings illustration'
Tag Archives: Python strings illustration
Python String
In this tutorial, we are going to learn Python String:
In Python, a string is a sequence of characters, enclosed within quotes. Strings can be created using single quotes ('...'
), double quotes ("..."
), or triple quotes ("""..."""
or '''...'''
). For example:
string1 = 'Hello, world!'
string2 = "This is a string."
string3 = '''This is a
multi-line
string.'''
In addition to creating strings, there are many built-in string methods in Python that allow you to manipulate and modify strings. For example, you can concatenate two strings using the +
operator:
greeting = "Hello"
name = "John"
message = greeting + " " + name
print(message) # Output: Hello John
There are many more string methods and functions available in Python, which you can explore in the Python documentation.
Accessing characters in Python String
In Python, you can access individual characters in a string using indexing. Indexing starts from 0 for the first character and goes up to the length of the string minus one. To access a character at a specific index, you can use square brackets []
with the index inside.
For example, let’s say you have a string my_string = "Hello, World!"
:
my_string = "Hello, World!"
print(my_string[0]) # Output: H
print(my_string[4]) # Output: o
print(my_string[-1]) # Output: !
In the first example, my_string[0]
returns the first character of the string, which is “H”. In the second example, my_string[4]
returns the fifth character, which is “o”. In the third example, my_string[-1]
returns the last character of the string, which is “!”. You can also use negative indexing to access characters from the end of the string, with -1
being the last character, -2
being the second to last character, and so on.
If you want to access a range of characters in a string, you can use slicing. Slicing uses the colon :
operator to specify the start and end indices of the substring you want to extract. For example:
my_string = "Hello, World!"
print(my_string[0:5]) # Output: Hello
print(my_string[7:]) # Output: World!
In the first example, my_string[0:5]
returns the substring from index 0 to index 4, which is “Hello”. In the second example, my_string[7:]
returns the substring from index 7 to the end of the string, which is “World!”.
Reversing a Python String
To reverse a string in Python, you can use string slicing with a step of -1. Here is an example:
my_string = "hello world"
reversed_string = my_string[::-1]
print(reversed_string)
This will output:
dlrow olleh
In this example, [::-1]
means “start at the end of the string, move to the beginning, and take each character with a step of -1 (i.e., backwards)”.
String Slicing
String slicing is a feature of many programming languages that allows you to extract a subset of characters from a string. It is a powerful tool for manipulating and analyzing strings, and can be used in a variety of ways.
In Python, for example, you can slice a string using the following syntax:
Syntex:
string[start:end:step]
where start
is the index of the first character to include in the slice, end
is the index of the first character to exclude from the slice, and step
is the number of characters to skip between each character in the slice.
For example, the following code will extract the first three characters from a string:
string = "Hello, World!"
slice = string[0:3]
print(slice)
Output:
Hel
You can also use negative indices to count from the end of the string:
string = "Hello, World!"
slice = string[-6:-1]
print(slice)
Output:
World
You can omit the start
or end
index to slice from the beginning or end of the string, respectively:
string = "Hello, World!"
slice = string[:5]
print(slice)
slice = string[7:]
print(slice)
Output:
Hello
World!
Finally, you can use a step
value to skip characters:
string = "Hello, World!"
slice = string[::2]
print(slice)
Output:
Hlo ol!
Note that the step
value can also be negative, in which case the slice will be returned in reverse order:
string = "Hello, World!"
slice = string[::-1]
print(slice)
Output:
!dlroW ,olleH
Deleting/Updating from a String
To delete or update a string in Python, you can use string methods or slicing. Here are some examples:
- Deleting a substring from a string: You can use the
replace()
method to delete a substring from a string by replacing it with an empty string. For example:
string = "Hello World"
new_string = string.replace("World", "")
print(new_string) # Output: "Hello "
- Updating a substring in a string: You can use slicing to update a substring in a string. For example:
string = "Hello World"
new_string = string[:5] + "Universe"
print(new_string) # Output: "Hello Universe"
In the above example, the first five characters of the string (“Hello “) are combined with the new substring (“Universe”) to create a new string.
Note that strings are immutable in Python, which means you cannot modify a string in-place. Instead, you must create a new string that contains the desired modifications.
Formatting of Strings
In Python, you can format strings using various methods. Here are some common ways to format strings:
- Using the
%
operator: This is an older method available in Python and is similar to the C language’s printf-style formatting.
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
Output:
My name is Alice and I am 25 years old.
2. Using the str.format()
method: This method provides more flexibility and is recommended for newer versions of Python (Python 3 onwards).
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is Alice and I am 25 years old.
You can also specify placeholders by index or name:
name = "Alice"
age = 25
print("My name is {0} and I am {1} years old. {0} {1}".format(name, age))
Output:
My name is Alice and I am 25 years old. Alice 25
3. Using f-strings (formatted string literals): This is a newer method introduced in Python 3.6, which provides a concise and readable way to format strings.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alice and I am 25 years old.
F-strings allow you to directly include variables and even evaluate expressions within curly braces.
a = 5
b = 3
print(f"The sum of {a} and {b} is {a + b}.")
Output:
The sum of 5 and 3 is 8.
These are just some of the most commonly used string formatting methods in Python. Each approach has its own advantages and can be used based on your preference and Python version.
Python String Built-In Function
Python provides a wide range of built-in functions that can be used to manipulate and operate on strings. Here are some commonly used string built-in functions:
- len(): Returns the length of a string. Example:
s = "Hello, World!"
length = len(s)
print(length) # Output: 13
2. lower(): Converts all characters in a string to lowercase. Example:
s = "Hello, World!"
lower_case = s.lower()
print(lower_case) # Output: hello, world!
3. upper(): Converts all characters in a string to uppercase. Example:
s = "Hello, World!"
upper_case = s.upper()
print(upper_case) # Output: HELLO, WORLD!
4. strip(): Removes leading and trailing whitespace characters from a string. Example:
s = " Hello, World! "
stripped = s.strip()
print(stripped) # Output: Hello, World!
5. split(): Splits a string into a list of substrings based on a delimiter. Example:
s = "Hello, World!"
split_list = s.split(", ")
print(split_list) # Output: ['Hello', 'World!']
6. join(): Joins the elements of an iterable (e.g., list) into a single string using a specified delimiter. Example:
lst = ['Hello', 'World!']
joined_string = ", ".join(lst)
print(joined_string) # Output: Hello, World!
7. replace(): Replaces all occurrences of a substring within a string with another substring. Example:
s = "Hello, World!"
replaced = s.replace("Hello", "Hi")
print(replaced) # Output: Hi, World!
8. find(): Returns the index of the first occurrence of a substring within a string (-1 if not found). Example
s = "Hello, World!"
index = s.find("World")
print(index) # Output: 7
These are just a few examples of Python’s string built-in functions. There are many more available that can help you manipulate and work with strings effectively.