Matlab 中是否有相当于 Python 的 f 字符串

问题描述 投票:0回答:1

我想知道是否有一种方法可以在 Matlab 中输入和格式化字符串,就像在 Python 中使用 f 字符串一样:

Python输入:

username = lemslems
text = f"Hello {username}!"

输出:

Hello lemslems!

我问这个是因为我讨厌用

%
格式编写,而且像我总是用 Python 那样编写它非常方便

python string matlab
1个回答
0
投票

Matlab 没有与 Python 的 f 字符串直接等效的功能,但您可以使用字符串格式化或连接来实现类似的功能。

实现此目的的一种方法是使用 sprintf 函数,它将数据格式化为字符串:

name = 'John';
age = 30;
formatted_string = sprintf('My name is %s and I am %d years old.', name, age);
disp(formatted_string);

或者,您可以使用字符串连接:

name = 'John';
age = 30;
formatted_string = ['My name is ', name, ' and I am ', num2str(age), ' years old.'];
disp(formatted_string);

两种方法都会产生以下输出:

My name is John and I am 30 years old.

这些方法允许您将变量插入到类似于 Python 中的 f 字符串的字符串中。

© www.soinside.com 2019 - 2024. All rights reserved.