MATLAB 字符串处理:大写转换、右对齐和空白处理
MATLAB 字符串处理:大写转换、右对齐和空白处理
本示例展示了在 MATLAB 中对字符串进行大写转换、右对齐以及处理空白字符的常用方法,并提供了相应的 Python 代码实现。
MATLAB 代码
% Work in upper case.
h = upper(h);
[m,n]=size(h);
% Right justify strings and form 2-D character array.
if ~isempty(find((h==' ' | h==0),1))
h = strjust(h);
% Replace any leading blanks and nulls by 0.
h(cumsum(h ~= ' ' & h ~= 0,2) == 0) = '0';
else
h = reshape(h,m,n);
end
Python 代码
# Work in upper case.
h = h.upper()
m, n = h.shape
# Right justify strings and form 2-D character array.
if ((h == ' ') | (h == '0')).any():
h = h.strjust()
# Replace any leading blanks and nulls by 0.
h[(h != ' ') & (h != '0')].cumsum(axis=1) == 0) = '0'
else:
h = h.reshape((m, n))
代码解析
-
大写转换:
- MATLAB:
h = upper(h); - Python:
h = h.upper()
- MATLAB:
-
右对齐:
- MATLAB:
h = strjust(h); - Python:
h = h.strjust()
- MATLAB:
-
空白处理:
- MATLAB:
h(cumsum(h ~= ' ' & h ~= 0,2) == 0) = '0';将所有前导空白和空字符替换为 '0'。 - Python:
h[(h != ' ') & (h != '0')].cumsum(axis=1) == 0) = '0'类似 MATLAB 的处理方式,将所有前导空白和空字符替换为 '0'。
- MATLAB:
-
二维数组:
- MATLAB:
h = reshape(h,m,n);将字符串转换为二维字符数组。 - Python:
h = h.reshape((m, n))将字符串转换为二维字符数组。
- MATLAB:
总结
本文展示了如何在 MATLAB 和 Python 中进行基本的字符串处理,包括大写转换、右对齐和处理空白字符。两种语言的代码实现方式有所不同,但最终实现的效果一致。
原文地址: https://www.cveoy.top/t/topic/qFHc 著作权归作者所有。请勿转载和采集!