[英]Python 3.x function:Converting string to list and printing output which excludes certain characters
我在嘗試將字符串轉換為列表並生成所需的輸出時遇到了麻煩。 到目前為止,我有以下代碼:
def func():
characters = '?/><,.:;"[]{}=+()*&^%$#@!' # keeping ' and -
new_lst = []
user = input("String: ")
for i in user:
if (i not in characters):
#new_lst = user.split(' ')
new_lst += i # I know this is the problem but I just don't know where to go from here
print(new_lst)
例如:
Keep. hyphen- and apostrophe's only.
電流輸出:
'K', 'e', 'e', 'p', ' ', 'h', 'y', 'p', 'h', 'e', 'n', '-', ' ', 'a', 'n', 'd', ' ', 'a', 'p', 'o', 's', 't', 'r', 'o', 'p', 'h', 'e', "'", 's', ' ', 'o', 'n', 'l', 'y']
所需的輸出:
['Keep', 'hyphen-', 'and', "apostrophe's", 'only']
謝謝你的幫助!
首先將句子分成單詞,然后遍歷單詞以(在內部循環中)重建修改過的單詞和(在外部循環中)單詞列表:
def func():
characters = '?/><,.:;"[]{}=+()*&^%$#@!' # keeping ' and -
new_lst = []
user = input("String: ")
for word in user.split():
x = ''
for i in word:
if (i not in characters):
x += i # I know this is the problem but I just don't know where to go from here
new_lst.append(x)
print(new_lst)
func()
輸出:
['Keep', 'hyphen-', 'and', "apostrophe's", 'only']
這不一定是一個代碼審查站點,但是我肯定會考慮更有意義地命名變量,並對內部循環使用列表理解:
def get_stripped_word_list(s):
"""Return a list of words in string s, excluding certain characters."""
# Sequence of characters to strip, keeping ' and -
characters = '?/><,.:;"[]{}=+()*&^%$#@!'
words = s.split()
modified_words = []
for word in words:
modified_word_letters = [c for c in word if c not in characters]
modified_words.append(''.join(modified_word_letters))
return modified_words
s = input("String: ")
print(get_stripped_word_list(s))
您可以替換字符,也可以拆分
def func():
characters = '?/><,.:;"[]{}=+()*&^%$#@!' # keeping ' and -
user = raw_input("String: ")
for i in characters:
user=user.replace(i,"")
new_lst=user.split(" ")
new_lst = [i.strip('.') for i in new_lst]
print(new_lst)
func()
輸出
['Keep', 'hyphen-', 'and', "apostrophe's", 'only']
您可以在re
模塊中使用sub
:
import re
string = "Keep. hyphen- and apostrophe's only."
re.sub("[^\w '-]", '', string).split()
Out[672]: ['Keep', 'hyphen-', 'and', "apostrophe's", 'only']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.