个性化阅读
专注于IT技术分析

Python字符串方法|S2(len,count,center,ljust,rjust,isalpha,isalnum,isspace和join)

下面的S3中介绍了一些字符串方法

字符串方法第1部分

本文讨论了更多方法

1. len():-此函数返回长度的字符串。

2. count(” string”, beg, end):-此功能计数提到的发生子串整个字符串。此函数接受3个参数substring, 开始位置(默认为0)和结束位置(默认为字符串长度)。

# Python code to demonstrate working of 
# len() and count()
str = "srcmini 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():-此功能用于用字符将字符串括起来重复弦的两端多次。默认情况下, 字符为空格。有两个参数, 字符串和字符的长度。

4. ljust():-这个函数返回左移的原始字符串,在它的右边有一个字符。它向左调整字符串。默认字符为空格。它还接受两个参数,字符串的长度和字符。

5. rjust():-这个函数返回向左移动一个字符的原始字符串。它正确地调整了弦。默认字符为空格。它还接受两个参数,字符串的长度和字符。

# Python code to demonstrate working of 
# center(), ljust() and rjust()
str = "srcmini"
   
# 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 : ---srcmini----
The string after ljust is : srcmini-------
The string after rjust is : -------srcmini

6. isalpha():-当字符串中的所有字符都为字母否则返回false。

7. isalnum():-当字符串中的所有字符都为数字和/或字母的组合否则返回false。

8. isspace():-当字符串中的所有字符都为空格否则返回false。

# Python code to demonstrate working of 
# isalpha(), isalnum(), isspace()
str = "srcmini"
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

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

赞(0) 打赏
未经允许不得转载:srcmini » Python字符串方法|S2(len,count,center,ljust,rjust,isalpha,isalnum,isspace和join)
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

微信扫一扫打赏