以下集合介绍了一些字符串方法。
字符串方法第1部分
字符串方法第2部分
本文讨论了更多方法
1. strip():-此方法用于删除所有开头和结尾其论点中提到的字符。
2. lstrip():-此方法用于删除所有开头其论点中提到的字符。
3. rstrip():-此方法用于删除所有尾随其论点中提到的字符。
# Python code to demonstrate working of
# strip(), lstrip() and rstrip()
str = "---srcmini---"
# using strip() to delete all '-'
print ( " String after stripping all '-' is : " , end = "")
print ( str .strip( '-' ) )
# using lstrip() to delete all trailing '-'
print ( " String after stripping all leading '-' is : " , end = "")
print ( str .lstrip( '-' ) )
# using rstrip() to delete all leading '-'
print ( " String after stripping all trailing '-' is : " , end = "")
print ( str .rstrip( '-' ) )
输出如下:
String after stripping all '-' is : srcmini
String after stripping all leading '-' is : srcmini---
String after stripping all trailing '-' is : ---srcmini
4.分钟(“字符串”):-此函数返回最小值字母从字符串。
5. max(“字串”):-此函数返回最大值字母从字符串。
# Python code to demonstrate working of
# min() and max()
str = "srcmini"
# using min() to print the smallest character
# prints 'e'
print ( "The minimum value character is : " + min ( str ))
# using max() to print the largest character
# prints 's'
print ( "The maximum value character is : " + max ( str ))
输出如下:
The minimum value character is : e
The maximum value character is : s
6. maketrans():-它用来将字符串1的内容与字符串2映射带有相应的索引, 稍后将使用translate()进行翻译。
7. translate():-这用来交换映射的字符串元素在maketrans()的帮助下。
# Python code to demonstrate working of
# maketrans() and translate()
from string import maketrans # for maketrans()
str = "srcmini"
str1 = "gfo"
str2 = "abc"
# using maktrans() to map elements of str2 with str1
mapped = maketrans( str1, str2 )
# using translate() to translate using the mapping
print "The string after translation using mapped elements is : "
print str .translate(mapped)
输出如下:
The string after translation using mapped elements is :
aeeksbcraeeks
在上面的代码中, 使用转换功能在字符串中将” g”替换为a, 将” f”替换为b, 将” o”替换为” c”。
8.replace():-此功能用于用新的子字符串替换子字符串在字符串中。该函数有3个参数。要替换的字符串, 将替换的新字符串以及表示替换操作限制的最大值(默认情况下为unlimited)。
# Python code to demonstrate working of
# replace()
str = "nerdsfornerds is for nerds"
str1 = "nerds"
str2 = "geeks"
# using replace() to replace str2 with str1 in str
# only changes 2 occurrences
print ( "The string after replacing strings is : " , end = "")
print ( str .replace( str1, str2, 2 ))
输出如下:
The string after replacing strings is : srcmini is for nerds
该方法是由
钦莫伊·伦卡(Chinmoy Lenka)
9. expandtabs()
:-它用来
用空格替换所有制表符(” \ t”)
或简单地使用给定的制表符大小来隔开, 这是可选的。
语法:string.tabsize(tabsize)
参数:指定一个制表符替换的字符数。默认情况下, 该函数的制表符大小为8。
返回值:一个字符串, 其中所有制表符都用空格替换。
# Python code to illustrate expandtabs()
string = 'GEEKS\tFOR\tGEEKS'
# No parameters, by default size is 8
print (string.expandtabs())
# tab size taken as 2
print (string.expandtabs( 2 ))
# tab size taken as 5
print (string.expandtabs( 5 ))
输出如下:
GEEKS FOR GEEKS
GEEKS FOR GEEKS
GEEKS FOR GEEKS
如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
来源:
https://www.srcmini02.com/69903.html