Python字符串

时间:2020-02-23 14:43:33  来源:igfitidea点击:

在本教程中,我们将学习Python String。

Python字符串

python是String最常见的数据类型之一。
" str"是python的内置字符串类。
字符串文字可以用单引号或者双引号引起来。
您可以在下面看到一些字符串文字的示例

literal1 = "This is the first literal"
literal2 = "This is the second literal"

访问Python字符串

您可以打印整个字符串或者字符串的特定部分,称为子字符串。
为此,您需要了解一些基础知识。
Python字符串从零开始索引。
这意味着如果字符串的大小为5,则元素的索引为0到4。
下面的代码将帮助您理解上下文。

word = "Tobacco"
#index: 0123456

#This will print the whole word
print(word)    	#Tobacco

#This will print the size of the string
print(len(word))	#7

#This will print the 0th element of the string which is T
print(word[0])	#T

#prints the 1st element (o) to 4th element (c) of the string
print(word[1:5])	#obac

#prints the substring from 3rd element to the end of the string
print(word[3:])	#acco

#prints from the 0th element to 2nd element of the string
print(word[:3])	#Tob

以下代码的输出将是

================== RESTART: /home/imtiaz/str.py ==================
Tobacco
7
T
obac
acco
Tob

串联python字符串

您可以通过在两个字符串之间放置一个" +"运算符来连接两个字符串。
您可以使用字符串连接数字,但条件是必须将数字更改为字符串。
您可以使用str()函数将数字转换为字符串。
以下示例将使您对此有所了解

str1 = "I love"
str2 = "I hate"
str3 = " you!"
#example of concatenation between two string
print(str1 + str3)

#this will give an error
#print("My age is "+15)

#after converting the number to a string, concatenate it with a string
print("My age is "+str(15))

以下代码的输出将是

更新Python字符串

Python字符串不允许更新字符串的元素。
但是,您可以尝试使用切片技术来创建具有更新的字符串特定索引的新字符串。
假设我们有一个单词" toek",但我们想使其成为" took"。
现在,看一下单词,需要更新的元素" e"位于索引2。
因此,我们可以对" e"之前和之后的子字符串进行切片,分别是" to"和" k"。
然后,我们可以将" to"与更新后的元素" o"连接起来,然后再将结果字符串与" k"连接起来。
所以代码将说明这个想法

str1 = 'toek'
print("Before Update:")
print(str1)

first = str1[:2] #that is 'to'
update = 'o'
last = str1[3:] #that is 'k'

str1 = first + update + last

print("After Update:")
print(str1)

输出将是

================== RESTART: /home/imtiaz/str3.py ==================
Before Update:
toek
After Update:
took
>>>

Python字符串方法

有一些方法可以操纵Python String。
您可以在此处找到所有官方的python字符串方法。
最常见的python字符串方法如下所示:

  • lower():返回字符串的小写版本

  • upper():返回字符串的大写版本

  • strip():返回从开头和结尾删除空格的字符串

  • isalnum():如果字符串中的所有字符都是字母数字并且至少有一个字符,则返回true,否则返回false。

  • isalpha():如果字符串中的所有字符都是字母并且至少包含一个字符,则返回true,否则返回false。

  • title():返回字符串的标题大小写版本,其中单词以大写字母开头,其余字符为小写字母。

  • join(list):使用字符串作为分隔符将给定列表中的元素连接在一起

  • find(substring):返回找到子字符串的字符串中的最低索引。
    如果未找到子字符串,则返回-1。

使用Python字符串的转义序列

您可以将转义序列放在字符串文字中以执行某些特殊任务。
假设您有两个单词" cat"和" dog"。
您想将它们放在一个字符串文字中,然后再放在单独的行中。
为此,您可以在两个单词之间添加" \ n"。
以下示例将帮助您理解。

task = 'cat\ndog'

print(task)

输出将在单独的行中打印"cat "和"狗"。
有一些转义序列。
如果您有兴趣,可以在这里找到

Python字符串包含

如果要检查字符串中是否存在子字符串,则可以使用in运算符,如下面的示例所示。

str1 = "I am here"

if "I" in str1:
  print("Found")
else:
  print("Not Found")

Python字符串拆分

有时我们用定界符得到一个长字符串,我们想将它们分成一个列表。
例如,在CSV数据中最常见。
我们可以为此使用字符串拆分功能。

x = "1,2,3"

y = x.split(",")

print(y)

它将在输出下方打印。

>>> 
================= RESTART: /Users/hyman/Desktop/string1.py =================
['1', '2', '3']
>>>