我是一个初学程序员,试图编写一个生成随机密码的python脚本.但是,即使我声明编码#utf-8,我总是得到一个非ASCII字符错误,如Stack Overflow中另一个类似的问题所述.这是源代码:
import string
import random
#coding: utf-8
print "Password generator will create a random customizable password."
print "Choose your options wisely."
number = int(input("How many letters do you want in your password?"))
caps = str(input("Do you want capital letters in your password? Y/N"))
symbols = str(input( "Do you want punctuation, numbers and other symbols in your password? Y/N"))
punctuation = ("!", ".", ":", ";", ",", "?", "'", "@", "£", "$", "«", "»", "~", "^","%", "#", "&", "/", range(0, 11)) …Run Code Online (Sandbox Code Playgroud) 我有这个代码,它应该逐个字符地读取文本文件,然后用它做一些事情,但是代码在第6行继续进行segfaulting.
#include <stdio.h>
int main(void)
{
printf("a\n");
FILE* fp = fopen("~/pset5/dictionaries/small", "r");
for (int a = fgetc(fp); a != EOF; a = fgetc(fp))
{
printf("b\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
肯定会发生一些奇怪的事情,因为它甚至不会打印"a\n"到终端,甚至printf在错误之前调用也很困难.我用gdb运行程序,这就是它失败的地方.
6 for (int a = fgetc(fp); a != EOF; a = fgetc(fp))
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
_IO_getc (fp=0x0) at getc.c:38
38 getc.c: No such file or directory.
Run Code Online (Sandbox Code Playgroud)
我也用valgrind运行它valgrind --leak-check=full ./test,测试是可执行文件的名称,这是相关的错误消息:
==7568== Invalid read of size 4
==7568== at 0x4EA8A21: getc …Run Code Online (Sandbox Code Playgroud) 我希望 name 保留行中剩余的所有字符,直到'\0'.
#include <stdio.h>
int main(){
char line[] = "1999-08-01,14.547,0.191,United Kingdom";
unsigned int year, month, day;
float temp, uncertainty;
char name[100];
sscanf(line, "%u - %u - %u, %f , %f , %s", &year, &month,
&day, &temp, &uncertainty, name);
printf("%u-%u-%u,%lf,%lf,%s\n", year, month, day, temp, uncertainty, name);
}
Run Code Online (Sandbox Code Playgroud)
我可以让这个工作像这样:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
char line[] = "1999-08-01,14.547,0.191,United Kingdom";
char* newline = malloc(strlen(line) + 2);
strcpy(newline, line);
newline[strlen(newline)] = '\n';
newline[strlen(newline)] = '\0';
unsigned int year, …Run Code Online (Sandbox Code Playgroud) 我想将0到9的整数转换为字符串。我可以通过手动转换每个数字来做到这一点:
str(1) = a
str(2) = b
Run Code Online (Sandbox Code Playgroud)
...一直到9。但是,这很慢,并且代码看起来不太像Python。我希望看到一种更快的编码解决方案,例如将所有这些数字放入列表中,然后将列表中的每个元素转换为字符串。我知道要列出清单,我应该这样做:
a = range(0,10)
Run Code Online (Sandbox Code Playgroud)
但是,我不知道如何将列表内的整数转换为字符串。在此先感谢您的帮助。