Python — Collections — 2 — Strings
Mastering String Python
Strings are one of the fundamental building blocks in Python. They represent a sequence of characters and are widely used in various applications, from simple text processing to machine learning and data analysis.
In this article, we’ll explore the key concepts of string operations in Python, with examples to make things clear.
Initilization of Strings :
1. Using Single or Double Quotes
You can create strings with either single (') or double (") quotes.
# Single quotes
string1 = 'Hello, World!'
# Double quotes
string2 = "Hello, Python!"
print(string1, string2)Hello, World! Hello, Python!2. Using Triple Quotes for Multi-line Strings
This is called a Doc string , this many provide documentation in the functions or Classes
Triple quotes (''' or """) are used to initialize multi-line strings.
multi_line_string = '''This is
a multi-line
string.'''
print(multi_line_string)This is
a multi-line
string.In Python, there are several ways to initialize a string depending on how the string is represented or formatted. Here’s a breakdown of different methods:
3. Initializing an Empty String
You can create an empty string using quotes with nothing inside.
empty_string = ""
print(empty_string) # Output: (nothing, it's an empty string)4. Using the str() Function
You can initialize a string from other data types using the str() function.
number = 42
string_from_number = str(number)
print(string_from_number) # Output: "42"5. Using Raw Strings
Raw strings, prefixed with r, treat backslashes (\) as literal characters, which is useful for file paths or regular expressions.
raw_string = r"C:\Users\NewFolder"
print(raw_string) # Output: "C:\Users\NewFolder"6. Using String Concatenation
You can initialize a string by concatenating multiple strings.
string1 = "Hello, "
string2 = "World!"
concatenated_string = string1 + string2
print(concatenated_string) # Output: "Hello, World!"7. Using String Multiplication
Strings can be initialized by repeating a character or a pattern using the * operator.
repeated_string = "A" * 5
print(repeated_string) # Output: "AAAAA"8. Using Format Strings —
You can initialize formatted strings using f-strings or the format() method.
this is one of the widely used if your doing mechine learning
# f-string
name = "Python"
formatted_string = f"Hello, {name}!"
print(formatted_string) # Output: "Hello, Python!"# format() method
formatted_string2 = "Hello, {}!".format(name)
print(formatted_string2) # Output: "Hello, Python!"9. Using Escape Characters
You can include special characters (like newlines, tabs, or quotes) by using escape sequences.
string_with_escape = "Hello, \"Python\"!\nWelcome to programming."
print(string_with_escape)10. Using bytes or bytearray
For string representations in binary, you can initialize a string as bytes.
byte_string = b"Hello, Bytes!"
print(byte_string) # Output: b'Hello, Bytes!'11. Using a List of Characters
You can initialize a string by joining a list of characters.
char_list = ['H', 'e', 'l', 'l', 'o']
string_from_list = ''.join(char_list)
print(string_from_list) # Output: "Hello"12. Using Template Strings (Advanced)
As a data analyst you dont need it ,
Get Faheem unnisa’s stories in your inbox
Join Medium for free to get updates from this writer.
Template strings allow substitution using placeholders. They are part of the string module.
from string import Template
template = Template("Hello, $name!")
string_from_template = template.substitute(name="Python")
print(string_from_template) # Output: "Hello, Python!"Summary:
Now the Operations in the string are similar to List , lets see more about about it
Operations in Strings
1. Accessing Characters (Indexing)
In Python, strings are indexed starting from 0 (left-to-right). You can also access characters from right-to-left using negative indices.
s = "Faheem"
print(s[0]) # Output: F (First character)
print(s[-1]) # Output: m (Last character)
print(s[3]) # Output: e (4th character)s[0]accesses the first character'F'.s[-1]accesses the last character'm'.s[3]accesses the 4th character'e'.
2. String Length
Use the len() function to find the number of characters in a string.
print(len(s)) # Output: 6- Here, the string
"Faheem"contains 6 characters.
3. Concatenation and Repetition
Combine or repeat strings using the + and * operators.
s2 = " Unnisa"
print(s + s2) # Output: Faheem Unnisa
print(s * 3) # Output: FaheemFaheemFaheems + s2concatenates two strings.s * 3repeats the string 3 times.
4. Checking Membership
You can check if a substring exists in a string using the in operator.
print("hee" in s) # Output: True
print("xyz" in s) # Output: False- The
inoperator searches for a substring inside the main string.
5. String Slicing
Slicing allows you to extract specific parts of a string using the syntax s[start:end:step].
- start: Starting index (inclusive)
- end: Ending index (exclusive)
- step: Interval for selection
Basic Slicing Examples:
print(s[1:4]) # Output: ahe (extracts characters from index 1 to 3)
print(s[:4]) # Output: Fahe (from start to index 3)
print(s[4:]) # Output: em (from index 4 to end)
print(s[::-1]) # Output: meehaF (reversing the string)6. Advanced Slicing
You can reverse specific parts of the string and select characters at custom intervals.
print(s[1:5][::-1]) # Output: heea (reverse specific part)
print(s[1:5:2]) # Output: ae (select characters at custom intervals)7. Iterating Over a String
You can loop through characters in a string using a for loop.
for char in s:
print(char, end=" ") # Output: F a h e e m- The
end=" "argument prints characters on the same line.
8. Encoding and ASCII Conversion
Python allows you to convert characters to and from their ASCII values.
Convert Characters to ASCII (Using ord):
print([ord(c) for c in s]) # Output: [70, 97, 104, 101, 101, 109]ord()converts characters like'F'to its ASCII value 70.
Convert ASCII to Characters (Using chr):
print("".join([chr(70), chr(97)])) # Output: Fachr()converts ASCII values back to characters.
Python String Methods
Summary of String Operations
Conclusion
- Python strings are powerful and flexible.
- You can access characters, slice strings, reverse, and manipulate them in various ways.
- Understanding these operations and methods will help you handle text more effectively in your projects and machine learning workflows.
Let me know your thoughts or if you have any questions!








