字符串是代表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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。