Iterate over words of a String in Python - GeeksforGeeks (2024)

Last Updated : 30 Mar, 2023

Summarize

Comments

Improve

Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string.

Examples:

Input: str = “GeeksforGeeks is a computer science portal for Geeks”
Output: GeeksforGeeks is a computer science portal for Geeks

Input: str = “Geeks for Geeks”
Output: Geeks for Geeks

Method 1: Using split() Using split() function, we can split the string into a list of words and is the most generic and recommended method if one wished to accomplish this particular task. But the drawback is that it fails in the cases in string contains punctuation marks.

Python3

# Python3 code to demonstrate

# to extract words from string

# using split()

# initializing string

test_string = "GeeksforGeeks is a computer science portal for Geeks"

# printing original string

print ("The original string is : " + test_string)

# using split()

# to extract words from string

res = test_string.split()

# printing result

print ("\nThe words of string are")

for i in res:

print(i)

Output

The original string is : GeeksforGeeks is a computer science portal for GeeksThe words of string areGeeksforGeeksisacomputerscienceportalforGeeks

Time complexity: O(n)
Auxiliary Space: O(n)

Method 2: Using re.findall() In the cases which contain all the special characters and punctuation marks, as discussed above, the conventional method of finding words in a string using split can fail and hence requires regular expressions to perform this task. findall() function returns the list after filtering the string and extracting words ignoring punctuation marks.

Python3

# Python3 code to demonstrate

# to extract words from string

# using regex( findall() )

import re

# initializing string

test_string = "GeeksforGeeks is a computer science portal for Geeks !!!"

# printing original string

print ("The original string is : " + test_string)

# using regex( findall() )

# to extract words from string

res = re.findall(r'\w+', test_string)

# printing result

print ("\nThe words of string are")

for i in res:

print(i)

Output

The original string is : GeeksforGeeks is a computer science portal for Geeks !!!The words of string areGeeksforGeeksisacomputerscienceportalforGeeks

Method 3: Using for loop and string slicing

Python3

# Initializing string

test_string = "GeeksforGeeks is a computer science portal for Geeks"

# Printing original string

print("The original string is: " + test_string)

# Using for loop and string slicing

start = 0

for i in range(len(test_string)):

if test_string[i] == ' ':

print(test_string[start:i])

start = i+1

print(test_string[start:])

#This code is contributed by Edula Vinay Kumar Reddy

Output

The original string is: GeeksforGeeks is a computer science portal for GeeksGeeksforGeeksisacomputerscienceportalforGeeks

This approach uses a for loop to iterate through the characters in the string and a variable to keep track of the starting index of the current word. When a space is encountered, the current word is printed and the starting index is updated to the next character. The last word in the string is printed outside the loop.

Time Complexity: O(n)
Auxiliary Space : O(n)

Method 4: Using the split() method with a regular expression

Use the split() method with a regular expression to split the string into words

Step-by-step approach:

  • Initialize a list to store the words extracted from the string.
  • Use the split() method with a regular expression to split the string into words.
  • Iterate over the words and append them to the list.
  • Print the list of words.

Follow the below steps to implement the above idea:

Python3

import re

# initializing string

test_string = "GeeksforGeeks is a computer science portal for Geeks !!!"

# printing original string

print ("The original string is : " + test_string)

# using split() method with a regular expression

# to extract words from string

res = re.split(r'\W+', test_string)

words = []

for word in res:

if word:

words.append(word)

# printing result

print ("\nThe words of string are")

for word in words:

print(word)

Output

The original string is : GeeksforGeeks is a computer science portal for Geeks !!!The words of string areGeeksforGeeksisacomputerscienceportalforGeeks

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n), where n is the length of the input string.



N

nikhilaggarwal3

Iterate over words of a String in Python - GeeksforGeeks (1)

Improve

Next Article

Iterate over characters of a string in Python

Please Login to comment...

Iterate over words of a String in Python - GeeksforGeeks (2024)
Top Articles
Payoneer Review [2024]: Features, Fees & Alternatives
10 Real Estate Metrics That Investors Should Know
Tabc On The Fly Final Exam Answers
Nfr Daysheet
Northern Whooping Crane Festival highlights conservation and collaboration in Fort Smith, N.W.T. | CBC News
B67 Bus Time
Best Pawn Shops Near Me
Tripadvisor Near Me
Turbocharged Cars
Used Wood Cook Stoves For Sale Craigslist
Sams Early Hours
Labor Gigs On Craigslist
Bitlife Tyrone's
Jellyfin Ps5
Craigslist Portland Oregon Motorcycles
Jalapeno Grill Ponca City Menu
Where Is The Nearest Popeyes
Costco Great Oaks Gas Price
Kountry Pumpkin 29
Craigslist Appomattox Va
bode - Bode frequency response of dynamic system
Skip The Games Fairbanks Alaska
Walgreens Alma School And Dynamite
Cincinnati Adult Search
Target Minute Clinic Hours
Chime Ssi Payment 2023
Rogue Lineage Uber Titles
Page 2383 – Christianity Today
Skidware Project Mugetsu
Truck from Finland, used truck for sale from Finland
The Powers Below Drop Rate
Craigslist Comes Clean: No More 'Adult Services,' Ever
Street Fighter 6 Nexus
Att U Verse Outage Map
Powerspec G512
Wattengel Funeral Home Meadow Drive
Daily Times-Advocate from Escondido, California
Blackstone Launchpad Ucf
Panorama Charter Portal
Oppenheimer Showtimes Near B&B Theatres Liberty Cinema 12
At Home Hourly Pay
'The Nun II' Ending Explained: Does the Immortal Valak Die This Time?
Studentvue Calexico
Euro area international trade in goods surplus €21.2 bn
Colin Donnell Lpsg
Blippi Park Carlsbad
Strawberry Lake Nd Cabins For Sale
786 Area Code -Get a Local Phone Number For Miami, Florida
2487872771
Sml Wikia
Gainswave Review Forum
Latest Posts
Article information

Author: Delena Feil

Last Updated:

Views: 6475

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.