非常简单快速的问题.以此列表为例:
a = ['hello1', 'hello2', 'hello3']
','.join(a)
Run Code Online (Sandbox Code Playgroud)
我希望在列表的最后一个元素之前使用'和'而不是逗号.所以我会得到:
你好1,你好2和你好3
代替....
你好1,你好2,你好3
有没有办法完成这个使用.join()?我知道我可以在列表中输入类似这样的简单示例,但我实际程序中需要的列表来自用户输入.
我试图使用牛顿方法返回k的平方根的最小值.
k=float(input("Number? "))
x = k/2
def newton(x):
while abs(x**(1/2)- k) >= 10**(-10):
if k >= 0:
x = (x+k/x)/(2)
return x
elif k < 0:
raise ValueError ("Cannot take the square root of a negative number")
print ("The approximate square root of", k, "is", newton(k))
print ("The error is", abs(x**(1/2)- k))
Run Code Online (Sandbox Code Playgroud)
但是,上面的代码只返回第一次迭代.例如,如果k是2,牛顿方法的准确平方根应该是1.41422,这是第三次迭代.但是,代码当前返回1.5,第一次迭代.如何返回1.41422而不是1.5的更精确的平方根?同样,错误需要反映这种变化.
Python 3.3中除了字符串的ValueError之外还有一种方法吗?如果我在k中键入一个字符串,我想要打印"无法将字符串转换为浮点数",而不是"不能取负数的平方根".
while True:
try:
k = float(input("Number? "))
Run Code Online (Sandbox Code Playgroud)
....
except ValueError:
print ("Cannot take the square root of a negative number")
break
except ValueError:
print ("Could not convert string to float")
break
Run Code Online (Sandbox Code Playgroud) 编译我的程序时,我不断收到此错误.这只是我代码的一小部分,因此如果需要,我将提供其余的代码.有关为何发生这种情况的任何想法?
void strip_quotes(char s[]) {
if (s[0]=='"') s=s+1;
if (s[strlen(s)-2]=='"') s[strlen(s)-2]=NULL;
}
Run Code Online (Sandbox Code Playgroud) 我注意到我的变量input2只打印字符串中的第一个单词,这导致程序其余部分出现问题(即不能正确打印名词).任何关于为什么会发生这种情况的见解将不胜感激
int main(int argc, char* argv[]){
char *input = strtok(argv[1], " \"\n");
//printf("%s\n", input);
int position;
int check = 0;
int first = 1;
while (input != NULL) {
position = binary_search(verbs, VERBS, input);
//printf("%s\n", input);
//printf("%d\n", position);
if (position != -1){
if (first){
printf("The verbs were:");
first = 0;
check = 1;
}
printf(" %s", input);
}
input = strtok(NULL, " ");
}
if (check == 1){
printf(".\n");
}
if (check == 0){
printf("There were no verbs!\n");
}
char …Run Code Online (Sandbox Code Playgroud)