Iterate over characters of a string in Python (original) (raw)
Last Updated : 27 Oct, 2024
In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a **loop. Let’s explore this approach.
Using for loop
The simplest way to iterate over the characters in a string is by using a for loop. This method is efficient and easy to understand.
Python `
s = "hello"
for char in s: print(char)
`
**Explanation: for char in s: This line loops through the string **s, with char representing each character in **s one by one.
Using enumerate for Index Access
If we need both the **character and its **index then enumerate() is a great choice. It returns both values in each iteration.
Python `
s = "hello"
for i, char in enumerate(s): print(f"Index {i}: {char}")
`
Output
Index 0: h Index 1: e Index 2: l Index 3: l Index 4: o
**Explanation:
- **enumerate(s) provides both the index **i and the character **char.
- The print function uses a formatted string, where the **f before the string allows us to include variables directly within it using **curly braces {}.
Similar Reads
- Python String A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut 6 min read
- Why are Python Strings Immutable? Strings in Python are "immutable" which means they can not be changed after they are created. Some other immutable data types are integers, float, boolean, etc. The immutability of Python string is very useful as it helps in hashing, performance optimization, safety, ease of use, etc. The article wi 5 min read
- Python - Modify Strings Python provides an wide range of built-in methods that make string manipulation simple and efficient. In this article, we'll explore several techniques for modifying strings in Python.Start with doing a simple string modification by changing the its case:Changing CaseOne of the simplest ways to modi 3 min read
Python String Manipulations
Python String Concatenation and Comparison
Python String Formatting
- Python String Methods Python string methods is a collection of in-built Python functions that operates on strings.Note: Every string method in Python does not change the original string instead returns a new string with the changed attributes. Python string is a sequence of Unicode characters that is enclosed in quotatio 5 min read
- Python String Exercise Basic String ProgramsCheck whether the string is Symmetrical or PalindromeFind length of StringReverse words in a given StringRemove i’th character from stringAvoid Spaces in string lengthPrint even length words in a stringUppercase Half StringCapitalize the first and last character of each word in 4 min read