def punctuation(x,y):
if len(x) == 0:
return y
if '.' in x[0]:
x[1] = x[1].capitalize()
return punctuation(x[1:],y.append(x[0]))
elif '!' in x[0]:
x[1] = x[1].capitalize()
return punctuation(x[1:],y.append(x[0]))
elif '?' in x[0]:
x[1] = x[1].capitalize()
return punctuation(x[1:],y.append(x[1]))
else:
return punctuation(x[1:],x[0])
z = ['!a','b']
punctuation(z,[])
希望获得['!a','b'],这意味着如果第一项包含(!,?,。),则第二项变为大写
Q3_p1 = "Enter the digit on the phone (0-9): "
Q3_p2 = "Enter the number of key presses (>0): "
def enter_msg(n):
x=raw_input(Q3_p1)
y=raw_input(Q3_p1)
Jay = Jay_chou(x,y)
return Jay
def Jay_chou(d,n):
if d==0: return " "
elif d==1: return [".", ",", "?"][n%3-1]
elif d==2: return ["a", "b", "c"][n%3-1]
elif d==3: return ["d", "e", "f"][n%3-1]
elif d==4: return ["g", "h", "i"][n%3-1]
elif d==5: return ["j", "k", "l"][n%3-1]
elif d==6: return ["m", "n", "o"][n%3-1]
elif d==7: return ["p", "q", "r", "s"][n%4-1]
elif d==8: return ["t", "u", "v"][n%3-1]
else: return ["w", "x", "y", "z"][n%4-1]
enter_msg(2)
我不知道为什么我得到错误 我明白这一点:
Enter the digit on the phone (0-9): 1
Enter the digit on the phone (0-9): 1
['1', '1']
TypeError: not all arguments converted during string formatting
答案 0 :(得分:1)
对于第二个问题:
您将字符串传递给Jay_Chou()
中的Jay = Jay_chou(x,y)
,而应传递整数。在您的情况下,n%3
部分实际上尝试进行字符串格式化而不是模数操作。
raw_input()
返回字符串,您需要使用int()
所以你得到这个错误:
In [13]: '1'%3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-39edc619f812> in <module>()
----> 1 '1'%3
TypeError: not all arguments converted during string formatting
试试这个:
Jay = Jay_chou(int(x),int(y))
然后输出:
Enter the digit on the phone (0-9): 3
Enter the digit on the phone (0-9): 4
d
#and for 1,1:
Enter the digit on the phone (0-9): 1
Enter the digit on the phone (0-9): 1
.
答案 1 :(得分:0)
对于第一个问题,您可以执行以下操作:
import itertools as it
the_list = ['a!', 'b']
result = [the_list[0]]
my_iter = iter(the_list)
next(my_iter) #my_iter.next() for python2
for i,(a,b) in enumerate(it.izip(the_list, my_iter)):
if set('.?!').intersection(a):
result.append(b.capitalize())
else:
result.append(b)
您的代码中的问题是您致电:
punctuation(x, y.append(something))
append
方法返回None
,因此递归调用的第二个参数类型错误。
你必须这样做:
y.append(something)
punctuation(x, y)