📜  Python中的 Collections.UserString

📅  最后修改于: 2022-05-13 01:55:25.376000             🧑  作者: Mango

Python中的 Collections.UserString

字符串是表示 Unicode字符的字节数组。但是, Python不支持字符数据类型。字符是长度为 1 的字符串。
例子:

Python3
# Python program to demonstrate
# string
 
# Creating a String 
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
   
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)


Python3
# Python program to demonstrate
# userstring
 
 
from collections import UserString
 
 
d = 12344
 
# Creating an UserDict
userS = UserString(d)
print(userS.data)
 
 
# Creating an empty UserDict
userS = UserString("")
print(userS.data)


Python3
# Python program to demonstrate
# userstring
  
 
from collections import UserString
  
 
# Creating a Mutable String
class Mystring(UserString):
     
    # 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
s1 = Mystring("Geeks")
print("Original String:", s1.data)
 
# Appending to string
s1.append("s")
print("String After Appending:", s1.data)
 
# Removing from string
s1.remove("e")
print("String after Removing:", s1.data)


输出:

String with the use of Single Quotes: 
Welcome to the Geeks World

String with the use of Double Quotes: 
I'm a Geek

注意:有关详细信息,请参阅Python字符串

Collections.UserString

Python支持 String ,例如集合模块中存在的名为UserString的容器。此类充当字符串对象的包装类。当一个人想要创建一个他们自己的带有一些修改功能或一些新功能的字符串时,这个类很有用。它可以被认为是为字符串添加新行为的一种方式。此类接受任何可以转换为字符串的参数并模拟其内容保存在常规字符串中的字符串。该字符串可通过此类的数据属性访问。
句法:

collections.UserString(seq)

示例 1:

Python3

# Python program to demonstrate
# userstring
 
 
from collections import UserString
 
 
d = 12344
 
# Creating an UserDict
userS = UserString(d)
print(userS.data)
 
 
# Creating an empty UserDict
userS = UserString("")
print(userS.data)

输出:

12344

示例 2:

Python3

# Python program to demonstrate
# userstring
  
 
from collections import UserString
  
 
# Creating a Mutable String
class Mystring(UserString):
     
    # 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
s1 = Mystring("Geeks")
print("Original String:", s1.data)
 
# Appending to string
s1.append("s")
print("String After Appending:", s1.data)
 
# Removing from string
s1.remove("e")
print("String after Removing:", s1.data)

输出:

Original String: Geeks
String After Appending: Geekss
String after Removing: Gkss