Python字符串方法 |设置 2(len、count、center、ljust、rjust、isalpha、isalnum、isspace 和 join)
下面的集合 3 中介绍了一些字符串方法
字符串方法第 1 部分
本文讨论了更多方法
1. len() :- 该函数返回字符串的长度。
2. count(“字符串”, beg, end) :- 该函数计算整个字符串中提到的子字符串的出现次数。此函数接受 3 个参数,s子字符串、开始位置(默认为 0)和结束位置(默认为字符串长度)。
# Python code to demonstrate working of
# len() and count()
str = "geeksforgeeks is for geeks"
# Printing length of string using len()
print (" The length of string is : ", len(str));
# Printing occurrence of "geeks" in string
# Prints 2 as it only checks till 15th element
print (" Number of appearance of ""geeks"" is : ",end="")
print (str.count("geeks",0,15))
输出:
The length of string is : 26
Number of appearance of geeks is : 2
3. center() :- 该函数用于将字符串字符在字符串两边重复多次。默认情况下,字符是空格。接受 2 个参数,字符串长度和字符。
4. ljust() :- 此函数返回向左移动的原始字符串,其右侧有一个字符。它向左调整字符串。默认情况下,字符是空格。它还接受两个参数,字符串长度和字符。
5. rjust() :- 此函数返回向右移动的原始字符串,其左侧有一个字符。它正确地调整了字符串。默认情况下,字符是空格。它还接受两个参数,字符串长度和字符。
# Python code to demonstrate working of
# center(), ljust() and rjust()
str = "geeksforgeeks"
# Printing the string after centering with '-'
print ("The string after centering with '-' is : ",end="")
print ( str.center(20,'-'))
# Printing the string after ljust()
print ("The string after ljust is : ",end="")
print ( str.ljust(20,'-'))
# Printing the string after rjust()
print ("The string after rjust is : ",end="")
print ( str.rjust(20,'-'))
输出:
The string after centering with '-' is : ---geeksforgeeks----
The string after ljust is : geeksforgeeks-------
The string after rjust is : -------geeksforgeeks
6. isalpha() :- 当字符串中的所有字符都是字母时,此函数返回 true,否则返回 false。
7. isalnum() :- 当字符串中的所有字符都是数字和/或字母的组合时,此函数返回 true,否则返回 false。
8. isspace() :- 当字符串中的所有字符都是空格时,此函数返回 true,否则返回 false。
# Python code to demonstrate working of
# isalpha(), isalnum(), isspace()
str = "geeksforgeeks"
str1 = "123"
# Checking if str has all alphabets
if (str.isalpha()):
print ("All characters are alphabets in str")
else : print ("All characters are not alphabets in str")
# Checking if str1 has all numbers
if (str1.isalnum()):
print ("All characters are numbers in str1")
else : print ("All characters are not numbers in str1")
# Checking if str1 has all spaces
if (str1.isspace()):
print ("All characters are spaces in str1")
else : print ("All characters are not spaces in str1")
输出:
All characters are alphabets in str
All characters are numbers in str1
All characters are not spaces in str1
9. join() :- 该函数用于将参数中提到的字符串序列与字符串连接起来。
# Python code to demonstrate working of
# join()
str = "_"
str1 = ( "geeks", "for", "geeks" )
# using join() to join sequence str1 with str
print ("The string after joining is : ", end="")
print ( str.join(str1))
输出:
The string after joining is : geeks_for_geeks