字符串操作
大小写操作:
定义字符 str
str.title():首字母大写
str.upper():全部字符大写
str.lower():全部字符小写
注意:Matlab 也有upper和lower 这两个关键字,目标一致,不过用法不同
% Matlab
>> a = "The dog is cute" ;
>> b = upper(a)
b =
"THE DOG IS CUTE"
>> c = lower(a)
c =
"the dog is cute"
# Python
ms_tr = ms.upper()
print(ms_tr)
字符串合并:
python 通过 + 实现
% Matlab
>> a = 'SK';
>> b = 'Ana';
>> c = a+b
error : 矩阵维度必须一致。
>> c = [a,b]
c =
'SKAna'
>> c=[a,' ',b]
c =
'SK Ana'
# Python
fr = "Ana";
sec = "DS";
print(fr+sec)
print(fr + " " + sec )
特殊符
\n:换行
\t:缩进
删除空白
str.rstrip():删除字符串末尾的空白
str.lstrip():删除字符串开头的空白
str.strip():删除字符串两边的空白
其它字符串操作命令
str.split():根据字符串创建一个单词列表
str.replace(‘原值’,‘新值’):字符串中某些字符可以被替换
字符串可被索引
str = 'asdfgher'
str[3]
Out[6]: 'f'
str[-2]
Out[7]: 'e'