𝗣𝘆𝘁𝗵𝗼𝗻 𝗦𝘁𝗿𝗶𝗻𝗴𝘀: 𝗜𝗻𝗱𝗲𝘅𝗶𝗻𝗴, 𝗦𝗹𝗶𝗰𝗶𝗻𝗴, 𝗮𝗻𝗱 𝗠𝗲𝘁𝗵𝗼𝗱𝘀
Strings are essential for Cloud, DevOps, and Automation. You need them to process logs, config files, and API responses.
A string is an ordered collection of characters. It is immutable. This means you cannot change a string after it exists.
𝗜𝗻𝗱𝗲𝘅𝗶𝗻𝗴 Every character has a position.
- Positive indexing starts from 0 on the left.
- Negative indexing starts from -1 on the right.
Example: text = "DevOps" text[0] gives D. text[-1] gives s.
𝗦𝗹𝗶𝗰𝗶𝗻𝗴 Slicing lets you extract parts of a string using the format: [start:stop:step].
- The start index is included.
- The stop index is excluded.
- The step is optional.
Examples:
- "DevOps"[0:3] gives Dev.
- "DevOps"[::2] gives Dvp.
- "DevOps"[::-1] reverses the string. This is a common way to check for palindromes.
𝗘𝘀𝘀𝗲𝗻𝘁𝗶𝗮𝗹 𝗠𝗲𝘁𝗵𝗼𝗱𝘀
- len(text): Returns the total character count.
- text.upper(): Converts everything to uppercase.
- text.lower(): Converts everything to lowercase.
- text.strip(): Removes whitespace or specific characters from both ends.
- text.split(): Turns a string into a list.
- " ".join(list): Turns a list back into a string.
- text.count("a"): Finds how many times "a" appears.
- text.find("a"): Returns the index of the first "a". It returns -1 if not found.
These small operations build the foundation for large automation scripts. Master these to write cleaner code.
Source: https://dev.to/tejas_shinkar/python-strings-indexing-slicing-and-essential-string-methods-3la0
Optional learning community: https://t.me/GyaanSetuAi