簡體   English   中英

在字符串單詞之間添加空格

[英]Adding a space between string words

編寫一個名為string_processing的 function,它將字符串列表作為輸入並返回一個沒有標點符號的全小寫字符串。 每個單詞之間應該有一個空格。 您不必檢查邊緣情況。

這是我的代碼:

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'])

我的 output:

'helloworld'
'testmeplease'

預期 output:

'hello world'
'test me please'

如何在單詞之間添加空格?

您只需將所有單詞分開,然后在它們之間用空格連接它們:

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

嘗試:

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'])

使用正則表達式:

import re
li = ['hello...,', 'world!']
st = " ".join(re.compile('\w+').findall("".join(li)))

使用正則re ,刪除每個非字母,然后join空格:

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']))

給出:

hello world
test me please

以下代碼可能會有所幫助。

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'])

我們可以使用 re 庫來處理單詞並在它們之間添加一個空格

import re
string = 'HelloWorld'
print(re.sub('([A-Z])', r' \1', string))

Output:

Hello World

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM