Python for loop with String

Simply put, a string in Python is a set of one or more characters. If you have learned all the other programming languages you will notice that single character is considered as character data type. But. In Python, single characters are always used as strings. So, in this tutorial, we will discuss Python for Loop with String.

That is, we will see how different operations are being performed using strings with Python for loop. But before that we will know a little bit about strings as much as we will use with Python for loop.

Python String

In Python, a string is made up of one or more characters. Here you must represent the string in a '...' single quote or "..." double quote. You can also use numbers instead of characters in strings. That is, whatever you put in a single quote or a double quote will be treated as a string.

To represent the Python string, you need to put single or double qoute on both sides of the string.

Each element of the string has a specific position which we call the index number. That is, each element of a string is arranged according to a specified sequence. And you can access each element of the string according to the sequence. So, look at this picture below, the whole concept will be clear.

To use Python for Loop with strings, strings must be arranged according to each element sequence.

Python String indexing

String indexing means accessing the elements of a string according to the index number. This is very important for you if you want to read Python for Loop with strings. I will divide this string indexing concept into three parts to make it easier for you.

  • String[index value]
  • String[start value, stop value]
  • String [start value, stop value, step value]

1. String [index value]

If you want to access a particular element from a string, you need to pass the position number of that particular element in the third bracket.

python for loop with string indexing

String = 'python'
print(String[0])
print(String[1]) 
print(String[4])
print(String[3])
print(String[6])

Output :

p
y
o
h
   print(String[6])
IndexError: string index out of range

2. String[start value, stop value]

If you want to access more than one element according to the sequence of a string, you need to pass the index number of the first character of that string sequence and the index number of the next character of the last character in the third bracket.

string argument with two arguments

String = 'python'
print(String[0:5])
print(String[1:])
print(String[:-1])
print(String[-6:-1])
print(String[0:])

Output :

pytho
ython
pytho
pytho
python

It’s a lot like a range function when both start and stop arguments are passed together. Here you can access the element before the stop argument.

3. String [start value, stop value, step value]

It is OK that you are accessing some part of a string, but you want to have a specified interval between each character in the part of that string. There you have to pass the step value with start and stop value in the third bracket.

string indexing with three arguments

String = 'python'
print(String[0::1])
print(String[5::-1])
print(String[0:6:2])
print(String[::])
print(String[:6:])

Output :

python
nohtyp
pto
python
python

Convert string to another data type

You can convert strings to different data types, for this you need to use your own type function of different data types such as list(), tuple(), set(), dict() etc.

String = 'python'
print(list(String))
print(set(String))
print(tuple(String))
print(dict(zip(String,'galaxy')))

Output :

['p', 'y', 't', 'h', 'o', 'n']
{'y', 'h', 'n', 't', 'o', 'p'}
('p', 'y', 't', 'h', 'o', 'n')
{'p': 'g', 'y': 'a', 't': 'l', 'h': 'a', 'o': 'x', 'n': 'y'}

You notice when the string is converted to set. Then not every element of the set is arranged according to the sequence. Because the set is unordered data collection. So, you can’t access every element in the set according to the sequence.

Second, you can use the split() method to convert a string to another data type. Here, using the split() method, first convert the string to a list and then convert the list to another data type such as set, tuple, etc.

String = 'python is programming language'
string_list = String.split(' ')
print(string_list)
print(tuple(string_list))
print(set(string_list))
print(dict(zip(string_list,range(len(string_list)))))

Output :

['python', 'is', 'programming', 'language']
('python', 'is', 'programming', 'language')
{'programming', 'python', 'is', 'language'}
{'python': 0, 'is': 1, 'programming': 2, 'language': 3}

Vice Versa, You can convert all other data types to strings using the join() method.

string_list = ['p', 'y', 't', 'h', 'o', 'n']
print(''.join(string_list))
string_tuple = ('p', 'y', 't', 'h', 'o', 'n')
print(' '.join(string_tuple))
string_set = {'p', 'o', 'h', 't', 'n', 'y'}
print(''.join(string_set))
string_dict = {'p': 'g', 'y': 'a', 't': 'l', 'h': 'a', 'o': 'x', 'n': 'y'}
print('_'.join(string_dict))

Output :

python
p y t h o n
hynopt
p_y_t_h_o_n

Many of you think that when a set is converted to a string using the Join method, its output will be python. But no, not every element of the set is arranged according to the sequence.

String methods and functions

I will discuss some methods of string. So, we will apply these methods later when we discuss Python for loop with string.

1. range() function

The first is the len() function. With the help of which you can measure the number of elements in an iterable object. So, if you use the length function in the case of a string, then you can understand how many characters(alphabets, digits, special characters) this string consists of.

string = 'pythongalaxy'
print(len(string))
string = 'python galaxy'
print(len(string))
string = 'pythongalaxy.com'
print(len(string))
string = 'pythongalaxy@0101'
print(len(string))

Output :

12
13
16
17

If you look at the program above, you will notice that every empty space, digit, and special character in the string is treated as an element.

And when we discuss Python for loop with string, this range function plays a very important role.

2. upper(), lower() and swapcase() function

You can use the upper() method to convert each character of the string to uppercase letters.

string = 'python'
print(string.upper())
string = 'python programming'
print(string.upper())

Output :

PYTHON
PYTHON PROGRAMMING

And with the lower() method, you can convert each element of the string into a lowercase letter.

string = 'PYTHON@1234'
print(string.lower())
string = 'Python For Loop With List'
print(string.lower())

Output :

python@1234
python for loop with list

Suppose the characters in a string are made up of uppercase and lowercase letters. And if you want to convert upper case letters to lower case letters and lower case letters to upper case letters then you need to use the swapcase() function with the string. Which acts as vice versa.

string = 'PYTHON galaxy'
print(string.swapcase())
string = 'Python For Loop With List'
print(string.swapcase())

Output :

python GALAXY
pYTHON fOR lOOP wITH lIST

3. title() function

Using the title() method, the first character of each word in the string will be converted to the upper case if the first character is in the lower case. For example

string = 'pthon galaxy'
print(string.title())
string = 'python for loop with list'
print(string.title())

Output :

Python Galaxy
Python For Loop With List

4. isupper(), islower() and istitle() function

The isupper() function will check if the string is in the upper case letter. If the string is in the upper case letter, it will return true, otherwise it will return false.

string = 'PYTHON123'
print(string.isupper())
string = 'python programming'
print(string.isupper())

Output :

True
False

Vice versa, if the string is in the lower case letter, it will return true, otherwise it will return false.

string = 'PYTHON 1234'
print(string.islower())
string = 'python for loop with list'
print(string.islower())

Output :

False
True

This istitle() function will return true if the first character of each word of the string is in the upper case letter, otherwise it will return false.

string = 'Python galaxy'
print(string.istitle())
string = 'Python For Loop With List'
print(string.istitle())

Output :

False
True

5. isdigit(), isalpha(), isalnum() and isspace() function

isdigit() method will return you true if each element of the string is a numeric digit, otherwise it will return false. For example

String = 'python 1234'
print(String.isdigit())
String = '9871234'
print(String.isdigit())
String = '7421 890'
print(String.isdigit())

Output :

False
True
False

The isalpha() method will check whether every element in the string is alphabetical. If each element is an alphabet then this method will return true, otherwise it will return false.

String = 'python'
print(String.isalpha())
String = 'python190'
print(String.isalpha())
String = '7890@123'
print(String.isalpha())

Output :

True
False
False

isalnum() method will return true if each character in the string is alpha numeric, otherwise it will return false.

String = 'python'
print(String.isalnum())
String = 'python3456'
print(String.isalnum())
String = '7543'
print(String.isalnum())
String = '7543 789'
print(String.isalnum())

Output :

True
True
True
False

isspace() method will return true if the whole string is filled with spaces, otherwise it will return false.

String = '  python  '
print(String.isspace())
String = '     '
print(String.isspace())
String = ' '
print(String.isspace())

Output :

False
True
True

6. replace(), split() and join() function

replace() method allows you to replace some part of a string with another sub-string.

String = 'pythongalaxy'
print(String.replace('python','physics'))
String = 'django743'
print(String.replace('743','786'))
String = 'java'
print(String.replace('java','python'))

Output :

physicsgalaxy
django786
python

split() method is used to convert large strings into smaller pieces. And the split method will return a list in which the strings with those small parts will be one of the elements of the list.

String = 'python galaxy'
print(String.split(' '))
String = 'Python-For-Loop-With-List'
print(String.split('-'))
String = 'Python@For@Loop@With@List'
print(String.split('@'))

Output :

['python', 'galaxy']
['Python', 'For', 'Loop', 'With', 'List']
['Python', 'For', 'Loop', 'With', 'List']

join() method allows you to convert more than one string to one string. And this join method may seem completely opposite to the split method.

Strin_list = ['python', 'galaxy']
String= ''.join(Strin_list)
print(String)
Strin_list = ('Python', 'For', 'Loop', 'With', 'List')
String= '-'.join(Strin_list)
print(String)
Strin_list=['Python', 'For', 'Loop', 'With', 'List']
String=' '.join(Strin_list)
print(String)

Output :

pythongalaxy
Python-For-Loop-With-List
Python For Loop With List

7. startwith() and endwith() function

The startwith() function will check if this string is started by the substring that you passed through this function.

Company= 'facebook'
print(Company.startswith('face'))
print(Company.startswith('fb'))
Company= '90facebook'
print(Company.startswith('90'))

Output :

True
False
True

The endwith() function will check if this string is terminated by the substring that you passed through this function.

Company= 'facebook'
print(Company.endswith('book'))
print(Company.endswith('fb'))
Company= 'facebook '
print(Company.endswith(' '))

Output : 

True
False
True

Why string is used with Python for loop

The question may come to your mind that we will use strings with Python for loop. Because many times you have to do the same thing over and over again while performing different operations on the string, in that case if you use the string with Python for loop then the task will be solved easily.

And the Python string is an iterable object, that is, each of its elements is lined up with the specified index number. So, for this you can use the string with Direct Python for Loop.

string indexing

Python for loop with string

You can use the string directly with the for loop. Or you can perform different operations using strings in range functions. So, notice that the syntax of Python for loop with string is given below.

syntax of python for loop with string

Alternatively, you can complete the process of Python for loop with string with help of iter() and next() functions.

You can access each element of the string with the help of iter and next function without using Python for loop with string.

So, notice that an example is given below. Here the string is first converted to iterator using the iter() function. And then every element has been accessed with the help of the next() function.

String = input('Enter a string : ')
S = iter(String)
print(next(S))
print(next(S))
print(next(S))
print(next(S))
print(next(S))
print(next(S))

Output :

Enter a string : python
p
y
t
h
o
n

Reversed String

In Python, a string is made up of one or more characters. And the sum of more than one character we call a word. Here you will see how to reverse the string using Python for loop with the string.

Not just characters here, when a string is made up of multiple words, you can reverse each word in the string. So, below I will take some examples and explain the whole concept, which will clear all your concepts.

1. How do you reverse a string using string indexing?

In this case, you have to pass -1 with the string as a step argument which is discussed above.

String = input('Enter a string : ')
print(String[::-1])

Output :

Enter a String : python galaxy
yxalag nohtyp

You can also take the help of For Loop.

String = input('Enter a string : ')
for var in String[::-1]:
    print(var, end='')

Output :

Enter a String : python galaxy
yxalag nohtyp

2. How do you reverse a string using the reversed function ?

One thing to note here is that the reverse object is always iterator. So, you can understand by looking at the program below.

String = input('Enter a string : ')
j = reversed(String)
print(next(j))
print(next(j))
print(next(j))
print(next(j))
print(next(j))
print(next(j))

Output :

Enter a string : python
n
o
h
t
y
p

The reverse object is the iterator. So, there is no need to use the iter() function here. And you can access the characters of the string from the opposite side by passing the reverse object directly into the next() function.

Here we will use the join() function. And pass the reverse object in the function.

String = input('Enter a string : ')
j = ''.join(reversed(String))
print(j)

Output :

Enter a string : python
nohtyp

You can also access one element after another from the opposite side of the string using the for loop with the reversed() function.

String = input('Enter a string : ')
for var in reversed(String):
    print(var)

Output :

Enter a string : python
n
o
h
t
y
p

3. Suppose a string consists of a sum of multiple words. How do you reverse each word of a string?

Here we use the split() method to convert each word of the string to an element in the list. And I will reverse each element of the list and convert it to a string again using the join() method.

String = input()
String_list = String.split(' ')
String_list1 = []
for var in String_list:
    String_list1.append(var[::-1])
S = ' '.join(String_list1)
print(S)

Output :

python for loop with string
nohtyp rof pool htiw gnirts

4. How do you reverse the whole string with the position of each word?

Here we will first convert each word in the string to an element in the list. And then I will reverse the positions of the elements in the list.

String = input()
String_list = String.split(' ')
String_list1 = []
for var in reversed(String_list):
    String_list1.append(var[::-1])
S = ' '.join(String_list1)
print(S)

Output :

python is the best programming language
egaugnal gnimmargorp tseb eht si nohtyp

5. Suppose you are told to reverse a particular word (In odd position) without reversing each word of the whole string.

Here we will reverse the words in odd position. For this, you need to use if-else condition in Python for loop.

String = input()
String_list = String.split(' ')
String_list1 = []
pos = 0
for var in String_list:
    if pos%2!= 0:
        String_list1.append(var[::-1])
    else:
        String_list1.append(var)
    pos+=1
S = ' '.join(String_list1)
print(S)

Output :

python for loop with string
python rof loop htiw string

You can also reverse the string in different ways. Here is just how you can reverse a string using Python for Loop.

Python for loop with string Examples

6. How to access the elements of a string with the help of for loop.

String = input('Enter a string : ')
for var in String:
    print(var)

Output :

Enter a string : money
m
o
n
e
y

7. How to separate alphabets and digits from an alphanumeric string.

String = input('Enter a alpha numeric string : ')
String_digit = ''
String_alpha = ''
for var in String:
    if var.isalpha():
        String_alpha +=var
    else:
        String_digit += var
print(String_alpha)
print(String_digit)

Output :

Enter a alpha numeric string : galaxy987123
galaxy
987123

8. Suppose you are given a numeric string. The question is how do you convert the sum of each digit in a string into a separate string.

String = input('Enter a numeric string : ')
String_sum = 0
for var in String:
    String_sum+=int(var)
print(str(String_sum))

Output :

Enter a numeric string : 234190
19

9. How to remove duplicate characters from a string.

String = input('Enter a string : ')
new_string = ''
for var in String:
    if var not in new_string:
        new_string+=var
print(new_string)

Output :

Enter a string : ppyytthhoonnnn
python

10. How do you access each character with an even index number from a string.

String = input('Enter a string : ')
for var in range(len(String)):
    if var%2==0:
         print(f'index number {var} ---> string char {String[var]}')

Output :

Enter a string : python
index number 0 ---> string char p
index number 2 ---> string char t
index number 4 ---> string char o

11. How do you remove empty spaces from a string ?

String = input('Enter a string : ')
new_string = ''
for var in String:
    if var.isspace():
        continue
    new_string+=var
print(new_string)

Output :

Enter a string : p y t h o n
python

If you want to know more about Python for Loop, you can read these two articles: Python for Loop with List and Range.

Conclusion

In Python we use the characters or words of the string in different ways in the program and also have a lot of problems, where we use Python for loop with the string.

And here are many examples on string so that you do not have difficulty understanding the concept. If I have been able to add some value in your life with the help of this tutorial, then you must share and comment.

Leave a Comment

Your email address will not be published. Required fields are marked *