格式化字符串的几种方式

1 使用占位符

简单记一下,这种方式输出不容易出错。

static void Main(string[] args)
{
    string stuName = "张晓晓";
    int stuAge = 20;
    //使用字符串拼接方法输出
    Console.WriteLine("学员姓名:" + stuName + "年龄:" + stuAge);
    //使用占位符方式输出(格式化输出)
    Console.WriteLine("学员姓名:{0}  年龄:{1}", stuName, stuAge);
    Console.ReadLine();
}

2 使用4.6中的语法糖

static void Main(string[] args)
{
    string stuName = "张晓晓";
    int stuAge = 20;
    //使用.NET 4.6引入的语法糖
    Console.WriteLine($"学员姓名:{stuName}  年龄:{stuAge}");
    Console.ReadLine();
}

参考资料:

  1. .NET/C#工控上位机VIP系统学习班【喜科堂互联教育】
### 字符串格式化的方法和方式 字符串格式化是编程中常见的需求,用于将变量或表达式嵌入到字符串中。以下是几种常见的字符串格式化方法及其特点: #### 1. `%` 格式化 `%` 格式化是最传统的字符串格式化方式之一。它使用类似于 C 语言中的 `printf` 风格的占位符。 ```python name = "Alice" age = 30 formatted_string = "My name is %s and I am %d years old." % (name, age) print(formatted_string) # 输出: My name is Alice and I am 30 years old. ``` 这种方式虽然简单,但在复杂场景下容易出错,且可读性较差[^1]。 #### 2. `str.format()` 方法 `str.format()` 是 Python 中引入的一种更灵活的字符串格式化方法。它支持位置参数、关键字参数以及复杂的格式化选项。 ```python name = "Alice" age = 30 formatted_string = "My name is {} and I am {} years old.".format(name, age) print(formatted_string) # 输出: My name is Alice and I am 30 years old. # 使用关键字参数 formatted_string = "My name is {name} and I am {age} years old.".format(name="Alice", age=30) print(formatted_string) # 输出: My name is Alice and I am 30 years old. ``` `str.format()` 提供了更好的可读性和灵活性,但性能略逊于其他方法[^1]。 #### 3. f-string 格式化(Python 3.6+) f-string 是 Python 3.6 引入的一种新型字符串格式化方式,通过在字符串前加 `f` 或 `F` 来启用。它允许直接在字符串中嵌入表达式。 ```python name = "Alice" age = 30 formatted_string = f"My name is {name} and I am {age} years old." print(formatted_string) # 输出: My name is Alice and I am 30 years old. # 嵌入表达式 formatted_string = f"Next year, I will be {age + 1} years old." print(formatted_string) # 输出: Next year, I will be 31 years old. ``` f-string 的语法简洁直观,性能优于 `%` 和 `str.format()`,并且支持嵌套表达式[^1]。 #### 4. 模板字符串 模板字符串是一种较为简单的字符串替换方式,适用于需要更简单的语法场景,如国际化(i18n)。 ```python from string import Template t = Template('$who likes $what') s = t.substitute(who='lu', what='ma') print(s) # 输出: lu likes ma ``` 模板字符串适合那些不需要复杂格式化的场景,尤其在需要简单替换时非常有用[^2]。 #### 5. C++ 中的 QString 格式化 在 C++ 中,QString 提供了多种字符串格式化方式。例如,`QString::number()` 可以将数字转换为字符串并进行格式化。 ```cpp double pi = 3.14159; QString piString = QString::number(pi, 'f', 2); // 保留两位小数 qDebug() << piString; // 输出: "3.14" ``` 此外,C++20 引入了 `std::format`,提供了类似 Python 的 `str.format()` 功能,但需要额外的支持[^3]。 ### 总结 - `%` 格式化:传统但不够直观。 - `str.format()`:灵活但性能稍逊。 - f-string:简洁高效,推荐在现代 Python 中使用。 - 模板字符串:适用于简单替换场景。 - C++ 中的 QString:提供多种方式,包括 `QString::number()` 和 `std::format`。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值