Python 中的collections.UserString

发布时间:2022-07-24

字符串是表示 Unicode 字符的字节。字符是长度为 1 的字符串。问题是 Python 不支持这种数据类型字符。 示例:

# First, we will create a String with a single Quotes
String_1 = 'JavaTpoint is the best platform to learn Python'
print("String with the use of Single Quotes: ")
print(String_1)
# Now, we will create a String with double Quotes
String_2 = "JavaTpoint is the best platform to learn Python"
print("\n String with the use of Double Quotes: ")
print(String_2)

输出

String with the use of Single Quotes: 
JavaTpoint is the best platform to learn Python
 String with the use of Double Quotes: 
JavaTpoint is the best platform to learn Python

collections.UserString

Python 提供了一个字符串作为容器,称为 UserString ,包含在collections模块中。这个类作为一个附加类来包装字符串对象。这个类在创建自己的字符串的情况下是有帮助的,这些字符串已经被修改,甚至有了新的特性。这是一个为字符串创建新功能的选项。此类可用于接受任何可转换为字符串的参数,并创建非结构化字符串的模拟,其内容存储在常规字符串中。该字符串可以通过其数据属性来访问。 语法: UserString的语法是:

collections.UserString(seq)

例 1:(带值且为空的用户字典)

from collections import UserString as US
P = 123546
# Here, we will create an UserDict
user_string = US(P)
print("UserString 1: ", user_string.data)
# Now, we will create an empty UserDict
user_string = US("")
print("UserString : ", user_string.data)

输出

UserString 1:  123546
UserString :  

例 2:可变字符串(追加函数和移除函数)

from collections import UserString as US
# Here, we will create a Mutable String
class User_string(US):
    # Function to append to string
    def append(self, s):
        self.data += s
    # Function to remove from string
    def remove(self, s):
        self.data = self.data.replace(s, "")
# Driver's code
s_1 = User_string("JavaTpoint")
print("The Original String: ", s_1.data)
# Here, we will Append to string
s_1.append("ing")
print("String After Appending: ", s_1.data)
# Here, we will Remove from string
s_1.remove("a")
print("String after Removing: ", s_1.data)

输出

The Original String:  JavaTpoint
String After Appending:  JavaTpointing
String after Removing:  JvTpointing

结论

在本教程中,我们已经讨论了如何在 Python 中使用“集合”模块的 UserString 函数。