Bootstrap FreeKB - Python (Scripting) - Looping over a string using split or splitlines
Python (Scripting) - Looping over a string using split or splitlines

Updated:   |  Python (Scripting) articles

Both split and splitlines can be used to loop through the elements in a string. In this example split is used to loop through the elements in the "foo" variable. split converts a string into a list.

#!/usr/bin/python3
foo = "Hello World"
items = foo.split()

print(f"items = {items}")

for item in items:
  print(f"item = {item}")

 

Which should output the following.

items = ['Hello', 'World']
item = Hello
item = World

 

Let's say the foo variable contains elements split by a new line. This might be a scenario where you would use splitlines because splitlines converts a string into a list, using newlines as the delimiter.

#!/usr/bin/python3
foo = "Hello World\nGoodbye World"
items = foo.splitlines()

print(f"items = {items}")

for item in items:
  print(f"item = {item}")

 

Which should output the following.

items = ['Hello World', 'Goodbye World']
item = Hello World
item = Goodbye World

 

Or you may want to go with split.

#!/usr/bin/python3
foo = "Hello World\nGoodbye World"
items = foo.split()

print(f"items = {items}")

for item in foo.split():
  print(f"item = {item}")

 

split will create a list where each item is a unique element in the list.

items = ['Hello', 'World', 'Goodbye', 'World']
item = Hello
item = World
item = Goodbye
item = World

 

Let's say the foo variable contains comma separated values.

foo = "Hello,World"

 

split can be used to loop over the variable, splitting at each comma.

for line in foo.split(','):
  print(line)

 

Or, sometimes this is even more practical. I think you need to be on Python version 3.8 or higher for this to work.

#!/usr/bin/python3
str = "Hello World"
foo, bar = str.split()
print(f"foo = {foo}") <- foo will contain Hello
print(f"bar = {bar}") <- bar will contain World

 

An if statement can be included to do something when a line contains a match.

for line in foo.split(','):
  if line.find('World') >= 0:
    print(line)

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ffe12b in the box below so that we can be sure you are a human.