1

How would I be able to split a word containing punctuation into 2 separate words without punctuation? For example if I have the string "half-attained", how would I make it so that I can remove the "-" as well as splitting the words into "half" and "attained".

This is what I have so far and it only removes the punctuation and puts the words together.

for n in range(0,len(test_list)):
  no_punct = ""
  for char in test_list[n]:
    if char not in punctuations:
        no_punct = no_punct + char
  no_puclist.append(no_punct)
Quinn Mortimer
  • 671
  • 6
  • 14
  • After seeing some of the answers, it might be best if you showed the punctuation string, which I assume has more than one character in it. All of the answers so far have assumed "-" is the only character to split on. – Quinn Mortimer Jan 16 '20 at 20:39
  • This question's accepted answer is pretty much what you need: https://stackoverflow.com/questions/4998629/split-string-with-multiple-delimiters-in-python – Quinn Mortimer Jan 16 '20 at 20:40

6 Answers6

1

split() returns a list of the words of a string separated along a separator.

In your case:

"half-attained".split("-")  
# ["half", "attained"]
k.wahome
  • 962
  • 5
  • 14
1

split() does it well

print( "half-attained".split("-")  )

# output :
# ["half", "attained"]
0

You should use split() :

string = "half-attained"
array = string.split("-")
print(array)

str.split(sep=None, maxsplit=-1) : Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

AmirHmZ
  • 516
  • 3
  • 22
0
"half-attained".split("-")  # ["half", "attained"]

Works fine. Read the docs next time.

Hack5
  • 3,244
  • 17
  • 37
0

split() splits string from separator characters and help you to get rid of those.

print("please-split-me".split("-")) 
# ["please" , "split" , "me"]
0

Are you trying to create an array or just another string with both words? Can you show your expected output?

You might simply need: test_list.replace('-', ' ')

Danosaure
  • 3,578
  • 4
  • 26
  • 41