Python | Rear stray character String split

Sometimes, while working with Python Strings, we can have problem in which we need to split a string. But sometimes, we can have a case in which we have after splitting a blank space at rear end of list. This is usually not desired. Lets discussed ways in which this can be avoided.

Method #1 : Using split() + rstrip()
The combination of above functions can be used to solve this problem. In this, we remove the stray character from the string before split(), to avoid the empty string in split list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Rear stray character String split
# Using split() + rstrip()
  
# initializing string
test_str = 'gfg, is, best, '
  
# printing original string
print("The original string is : " + test_str)
  
# Rear stray character String split
# Using split() + rstrip()
res = test_str.rstrip(', ').split(', ')
  
# printing result 
print("The evaluated result is : " + str(res)) 

chevron_right


Output :

The original string is : gfg, is, best,
The evaluated result is : ['gfg', 'is', 'best']

 

Method #2 : Using split()
The use of rstrip() can be avoided by passing additional arguments while performing the split().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Rear stray character String split
# Using split()
  
# initializing string
test_str = 'gfg, is, best, '
  
# printing original string
print("The original string is : " + test_str)
  
# Rear stray character String split
# Using split()
res = test_str.split(', ')[0:-1]
  
# printing result 
print("The evaluated result is : " + str(res)) 

chevron_right


Output :

The original string is : gfg, is, best,
The evaluated result is : ['gfg', 'is', 'best']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.