Write a function named
string_processing
that takes a list of strings as input and returns an all-lowercase string with no punctuation. There should be a space between each word. You do not have to check for edge cases.
Here is my code:
import string
def string_processing(string_list):
str1 = ""
for word in string_list:
str1 += ''.join(x for x in word if x not in string.punctuation)
return str1
string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])
My output:
'helloworld'
'testmeplease'
Expected output:
'hello world'
'test me please'
How to add a space in just between words?
You just need to keep all the words separate and then join them later with a space between them:
import string
def string_processing(string_list):
ret = []
for word in string_list:
ret.append(''.join(x for x in word if x not in string.punctuation))
return ' '.join(ret)
print(string_processing(['hello,', 'world!']))
print(string_processing(['test...', 'me....', 'please']))
Output:
hello world
test me please
Try:
import string
def string_processing(string_list):
str1 = ""
for word in string_list:
st = ''.join(x for x in word if x not in string.punctuation)
str1 += f"{st} " #<-------- here
return str1.rstrip() #<------- here
string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])
using regex:
import re
li = ['hello...,', 'world!']
st = " ".join(re.compile('\w+').findall("".join(li)))
Using re
gex , remove every non-letter and then join
with a space:
import re
def string_processing(string_list):
return ' '.join(re.sub(r'[^a-zA-Z]', '', word) for word in string_list)
print(string_processing(['hello,', 'world!']))
print(string_processing(['test...', 'me....', 'please']))
Gives:
hello world
test me please
The following code could help.
import string
def string_processing(string_list):
for i,word in enumerate(string_list):
string_list[i] = word.translate(str.maketrans('', '', string.punctuation)).lower()
str1 = " ".join(string_list)
return str1
string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])
We can use the re library to process the words and add a space between them
import re
string = 'HelloWorld'
print(re.sub('([A-Z])', r' \1', string))
Output:
Hello World
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.