如何在 Python 中获取一个以空格填充的字符串,并使原始字符串右对齐?
字符串是一系列字符,可以表示单个单词或完整的短语。在 Python 中,我们可以在没有数据类型说明符的情况下声明字符串或任何其他数据类型。因此,与 Java 相比,在 Python 中使用字符串更容易。
Python 中的字符串由名为 String 的类表示。此类提供多个函数和方法,您可以使用这些函数和方法对字符串执行各种操作。
在本文中,我们将重点介绍如何在 Python 中获取一个以空格填充的字符串,并使原始字符串右对齐。
使用 rjust() 方法
Python 的 rjust() 方法用于将字符串与指定数量的位置右对齐。以下是此函数的语法:
string.rjust(length, character)
其中,
length 是您想要填充的空格数(此数字包含字符串的长度;如果数字小于字符串的长度,则不会进行任何更改)。
character 是一个可选参数,用于使用指定的字符填充空格(如果未指定字符,则会填充空格)。
示例 1
在下面给出的程序中,我们使用 rjust 方法用空格填充给定的字符串。
str1 = "Welcome to Tutorialspoint" str2 = str1.rjust(30) print("Padding the string: ",str1) print(str2)
输出
上述程序的输出为:
('Padding the string: ', 'Welcome to Tutorialspoint')
Welcome to Tutorialspoint
示例 2
在下面给出的示例中,我们使用 rjust 方法用符号“$”填充给定的字符串。
str1 = "Welcome to Tutorialspoint" str2 = str1.rjust(30,'$') print("Padding the string ",str1) print(str2)
输出
上面给出的示例的输出为:
('Padding the string ', 'Welcome to Tutorialspoint')
$$$$$Welcome to Tutorialspoint
示例 3
在下面给出的示例中,我们使用 rjust 并用符号“0”填充字符串的左侧。
str1 = "this is string example....wow!!!"; print(str1.rjust(50, '0'))
输出
上面给出的程序的输出为:
000000000000000000this is string example....wow!!!
使用 format() 方法
Python 的 format() 方法是下一个选项。为了填充空白并填充字符串,我们可以使用字符串格式化技术。此方法通常与 print 语句一起使用。
我们将使用冒号 (:) 来指示需要填充的括号中空格的数量,以便提供正确的填充。要添加左填充,我们还应该添加 > 符号。
示例
在下面给出的示例中,我们获取一个字符串作为输入,并使用 format 方法填充字符串的左侧。
str1 = "Welcome to Tutorialspoint" str2 = ('{:>35}'.format(str1)) print("Left Padding of the string ",str1) print(str2)
输出
上述程序的输出为:
('Left Padding of the string ', 'Welcome to Tutorialspoint')
Welcome to Tutorialspoint
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP