Python中的Collections.UserString

Python中的Collections.UserString

字符串 是表示Unicode字符的字节。字符是长度为一的字符串。问题是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 的字符串容器,包含在集合模块中。该类函数作为一个包裹在字符串对象周围的附加类。在创建自己修改或具有新功能的字符串的情况下,该类非常有用。它是创建字符串新特性的选项。该类可以用于接受任何可以转换为字符串的参数,并创建一个模拟结构不确定的字符串,其内容存储在一个常规字符串中。可以通过其数据属性访问该字符串。

语法:

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中使用”collections”模块的UserString函数。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程