python中的字符串的操作和c語言就有很大的不同了,倒是覺得和matlib相似。python支持用成對的單引號或雙引號,三引號用來包含特殊字符:
str = 'python is number 1'
print(str)
輸出:python is number 1
python中字符串的引用和切片操作非常方便,值得一提的是,python中第一個字符的索引是0,最後一個字符的索引是-1:
str = 'python is number 1'#輸出python is number 1
str_0 = str[0] #輸出p
str_1 = str[1] #輸出y
str_2 = str[-1] #輸出1
str_3 = str[2:5] #輸出第2到第5個字符:tho
str_4 = str[:7] #從第0個字符輸出到第七個字符:python
str_5 = str[9:] #從第9個字符一直輸出到最後一個字符:number 1
c語言的話,要將字符串存入數組,然後通過循環體才能將指定長度的字符串輸出,並不像python這樣一個語句就搞定的
int i;
char a[] = "c is number 1";
for (i = 0; i<=7; i++)
{
putchar(a[i]);
}
輸出第0項到第7項:c is num
二、字符串的組合
這個更方便…兩個字符串相加就行:
str = 'python is number 1'
str_1 = 'c is number 1'
str_2 = ' or '
str_3 = "?"
str = str + str_2 + str_1 + str_3
print(str)
輸出結果是:python is number 1 or c is number 1?
很方便很僞代碼有木有,c語言的話,需要用strcat(前一個字符串,後一個字符串)這個函數,或者用循環體,就不演示了