當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Collections.UserString用法及代碼示例


字符串是代表Unicode字符的字節數組。但是,Python不支持字符數據類型。字符是長度為一的字符串。

例:

# 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) 

輸出:



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,如collections模塊中存在一個名為UserString的容器。此類充當字符串對象的包裝器類。當一個人想要創建自己的帶有某些修改函數或某些新函數的字符串時,此類非常有用。它可以被視為為字符串添加新行為的一種方式。此類采用任何可以轉換為字符串的參數,並模擬其內容保留在常規字符串中的字符串。該類的data屬性可以訪問該字符串。

用法:

collections.UserString(seq)

範例1:

# 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:

# 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 rmeove 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



相關用法


注:本文由純淨天空篩選整理自nikhilaggarwal3大神的英文原創作品 Collections.UserString in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。