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
Coinbase Crypto Wallet Review
6 crypto gems to buy in 2023
SZA: Weinen und töten und alles dazwischen
Mcgeorge Academic Calendar
Danatar Gym
Access-A-Ride – ACCESS NYC
Alan Miller Jewelers Oregon Ohio
Kraziithegreat
Geodis Logistic Joliet/Topco
Dr Doe's Chemistry Quiz Answer Key
Tyrunt
Thotsbook Com
Nitti Sanitation Holiday Schedule
Meritas Health Patient Portal
Belle Delphine Boobs
Free Online Games on CrazyGames | Play Now!
Fraction Button On Ti-84 Plus Ce
Ally Joann
Jc Green Obits
Deshuesadero El Pulpo
Chicago Based Pizza Chain Familiarly
Jayme's Upscale Resale Abilene Photos
Nottingham Forest News Now
Firefly Festival Logan Iowa
Wolfwalkers 123Movies
Federal Express Drop Off Center Near Me
Gncc Live Timing And Scoring
Bfri Forum
La Qua Brothers Funeral Home
Fastpitch Softball Pitching Tips for Beginners Part 1 | STACK
Wega Kit Filtros Fiat Cronos Argo 1.8 E-torq + Aceite 5w30 5l
Navigating change - the workplace of tomorrow - key takeaways
B.k. Miller Chitterlings
Trebuchet Gizmo Answer Key
Asian Grocery Williamsburg Va
Naya Padkar Newspaper Today
What Does Code 898 Mean On Irs Transcript
Directions To The Closest Auto Parts Store
Kent And Pelczar Obituaries
Subdomain Finder
Exploring the Digital Marketplace: A Guide to Craigslist Miami
Hanco*ck County Ms Busted Newspaper
Brown launches digital hub to expand community, career exploration for students, alumni
Ehc Workspace Login
Dagelijkse hooikoortsradar: deze pollen zitten nu in de lucht
Zipformsonline Plus Login
Hello – Cornerstone Chapel
The Pretty Kitty Tanglewood
Mlb Hitting Streak Record Holder Crossword Clue
Doelpuntenteller Robert Mühren eindigt op 38: "Afsluiten in stijl toch?"
Bluebird Valuation Appraiser Login
Appsanywhere Mst
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.