Python program to extract characters in given range from a string list

When it is required to extract characters in a given range from a string list, we can use list comprehension and string slicing. This technique allows us to join all strings and extract a specific portion based on character positions.

Example

Below is a demonstration of extracting characters from position 11 to 25 ?

my_list = ["python", "is", "fun", "to", "learn"]

print("The list is :")
print(my_list)

start, end = 11, 25

my_result = ''.join([element for element in my_list])[start : end]

print("The result is :")
print(my_result)

Output

The list is :
['python', 'is', 'fun', 'to', 'learn']
The result is :
tolearn

How It Works

The process involves three main steps:

  • A list of strings is defined and displayed on the console.

  • The values for 'start' and 'end' indices are defined (11 and 25 respectively).

  • List comprehension iterates over each element, join() concatenates all strings into one, and slicing [start:end] extracts characters from position 11 to 24.

  • The extracted substring is assigned to a variable and displayed.

Alternative Approach

You can also extract characters with a more explicit approach ?

words = ["hello", "world", "python", "programming"]

# Join all strings first
combined_string = ''.join(words)
print("Combined string:", combined_string)

# Extract characters from index 5 to 15
start, end = 5, 15
extracted = combined_string[start:end]

print(f"Characters from {start} to {end}: {extracted}")
Combined string: helloworldpythonprogramming
Characters from 5 to 15: worldpytho

Conclusion

Use ''.join() with list comprehension to concatenate strings, then apply slicing to extract characters within a specific range. This method is efficient for processing string lists when you need character-level extraction.

Updated on: 2026-03-26T01:23:51+05:30

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements