计划任务:
代码:
import string
str1 = "abc, 'bca'"
str2 = "abc, 'bca'"
str2.strip(string.punctuation)
str2.split()
list1 = []
list2 = []
for s in str1:
list1.append(s)
for s in str2:
list2.append(s)
print(list1)
print(list2)
print(string.punctuation)
结果:
['a', 'b', 'c', ',', ' ', "'", 'b', 'c', 'a', "'"] #list1
['a', 'b', 'c', ',', ' ', "'", 'b', 'c', 'a', "'"] #list2
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ #string.punctuation
list2不应该有任何空格或标点符号。为什么它返回与未剥离的未分割列表相同的值?
答案 0 :(得分:1)
你犯了两个错误:
您忽略 str.strip()
和str.split()
的返回值。字符串是不可变的,这些方法返回 new 对象。
您正在剥离,然后拆分,在字之间留下标点,因为剥离只会从开头和结尾删除字符。
首先拆分,然后剥离并存储结果:
result = [word.strip(string.punctuation) for word in str2.split()]
我使用list comprehension依次处理str2.split()
来电中的每个结果:
>>> import string
>>> str2 = "abc, 'bca'"
>>> [word.strip(string.punctuation) for word in str2.split()]
['abc', 'bca']
答案 1 :(得分:0)
删除所有标点符号并将string2拆分为单词
然后将每个单词放入list2
然后,您可以:
>>> ''.join([i for i in str2 if i not in string.punctuation])
'abc bca'
- 将string1的每个单词放在list1
中 醇>
我不明白这个。
顺便说一句,记住分配结果,否则你会丢失它们。
str2.strip(string.punctuation)
str2.split()
list1 == list2的原因是你只是将str1和str2中的每个元素添加到list1和list2,str1等于str2,所以list1等于list2