[英]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.