Happy journey of simple Python: string operation of Python basic syntax

Defonds 2020-11-13 04:52:49
happy journey simple python string



This series of string manipulation topics mainly include how to use Python Examples of using strings in programming . Here you can learn how to initialize a string , Get string length , Get its substring , Remove the space in the string , Case conversion and replacement of substrings in strings, etc .

1. Print string to console output

have access to print() Function to print a string to the console .Python Of print() The function syntax is as follows :

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

among ,

  • objects Represents the output of multiple objects at a time . Multiple objects are separated by commas
  • sep Separator between objects when output . It can be a string or a single character . Default is space
  • end The object appended to the output statement . It can be a string or a single character . The default is line break \n
  • file File object to write . The default is sys.stdout, The system standard output : Console output
  • flush Whether to input the output statement to the parameter immediately file In the object pointed to . It can be True or False. The default is False
    You can override by providing the corresponding parameters sependfile or flush The default value of . Next, let's demonstrate with examples .

1.1. Basic output statement

 Basic output statement .png
In the above example, we give print Statement provides two objects , The default separator is space , Since the default end The character is a newline , So we print out Hello and World, The middle is separated by a space , It ends with a new line .

1.2. Custom delimiter

 Custom delimiter .png
In the above example, we customize a character as a separator , So the default separator ( Space ) Will be covered . Of course , You can also use a string as a separator :

1.3. Custom Terminator

 Custom Terminator .jpg
In the above example, we define a character as the Terminator , So the default Terminator ( Line break ) Will be covered .

2. Python An example of string length

To calculate the length of a string, you need to pass the string as an argument to len() function .len() Function returns an integer representing the length of a given string .
len() The syntax of the function is :

len(mystring)

among mystring It's a string that needs to calculate its length .
In the following example, we use len() Function to calculate the length of a string .

# Python String Length Example
mystring = 'python examples'
length = len(mystring)
print('length of the string is:', length)

Execution and output :
 Calculate its length .png
If you want to output the length of an empty string ,len() Will return to zero .

mystring = ''
length = len(mystring)
print('length of the string is:', length)

Execution and output :
 Output the length of an empty string .jpg

3. Examples of substrings

stay Python We can get the substring by cutting . The syntax of string cutting is :

mystring[a:b]

mystring[a:b] Will return mystring In the from a To b String .
In the next example , We use the above syntax to cut the 8 To 12 Substring between :

# Python Substring Example
mystring = 'defonds.blog.csdn.net'
substring = mystring[8:12]
print(substring)

Execution and output :
 Substring interception .jpg
From this we can see that mystring start index by 0,mystring[a:b] The intercept is mystring Of the a To the first b - 1 Characters . This behavior is consistent with other languages .

4. Remove the spaces at the beginning and end of a string

To remove the spaces that appear at the beginning and end of a string , have access to strip() function . In the following example, we assign a string variable with spaces at the beginning and the end , And then we use strip() Function to remove the space around the string :

# Python Strip() – Remove White Spaces at Start and End of String
mystring = ' python examples '
cleanstring = mystring.strip()
# before strip
print(mystring)
print(len(mystring))
# after strip
print(cleanstring)
print(len(cleanstring))

Execution and output :
 Remove the spaces at the beginning and end of a string .jpg

5. String case conversion

To convert all characters in a string to lowercase , have access to lower() Method ; To convert it all to uppercase , have access to upper() Method . Here is an example of converting a string to case .

# Python Convert String to Lowercase or Uppercase Example
mystring = 'Python Examples'
print('Original String:', mystring)
lowercase = mystring.lower()
uppercase = mystring.upper()
print('Lowercase String:', lowercase)
print('Uppercase String:', uppercase)

Execution and output :
 String case conversion .jpg

6. String substitution

have access to replace() Method to replace a string .replace() The syntax of the method is as follows :

str.replace(old, new [, count])

among ,old by str You want to be... In a string new Replace the string with count Second string .count Variable optional . So if you don't offer count Parameters , all old Where it appears, it will be replaced with new. Note that there old String matching is case sensitive .

6.1. Basic replacement of strings

In the next example , We use replace() Method to set all the Examples Replace with Programs.

# Python Replace String Examples
mystring = 'Python Examples. Examples for basic and advanced concepts'
print('Original String:', mystring)
newstr = mystring.replace('Examples', 'Programs')
print('New String:', newstr)

Execution and output :
 A basic example of string substitution .jpg

6.2. Replace only a specified number of times

Let's take an example of replacing only a specified number of times :

mystring = 'Python Examples. Examples. Examples. Examples. Examples. Examples.'
print('Original String:', mystring)
newstr = mystring.replace('Examples', 'Programs', 3)
print('New String:', newstr)

Execution and output :
 Replace only a specified number of times .jpg
You can see ,Examples There is 6 Time , Only the front 3 Times have been replaced .

7. Use the delimiter to split the string

You can use built-in split() Method to use the delimiter to split a string .split() The syntax of the method is as follows :

str.split(separator, maxsplit)

among ,str Is the string to be split
separator Is the delimiter for string segmentation . If no delimiter is specified , that str The string will return as a whole , That is to say, there is only one element in the list of segmentation results , namely str character string . And if there are spaces in the string , The space between characters is used as the delimiter , Return the linked characters as a whole , No matter how many spaces there are between them, it will be used as a delimiter .
maxsplit Is the maximum number of splits that can be done . If not provided , Then complete the most possible split .

7.1. Example of string cutting

In the next example , We define a string separated by commas , We're going to use commas as as the delimiter to divide it , And store the results in a variable .

# Python Split String by Delimiter
str = 'Python,Examples,Programs,Code,Programming'
chunks = str.split(',')
print(chunks)

Execution and output :
 Example of string cutting .png

7.2. Limited maximum number of segmentation

Next, let's take the comma as the delimiter string as an example , We set the maximum number of segmentation as 3

# Python Example to Split String with limited maxsplit
str = 'Python,Examples,Programs,Code,Programming'
chunks = str.split(',', 3)
print(chunks)

Execution and output :
 Limited maximum number of segmentation .png
The string qualifier has 4 individual , It can be split up to four times , It can be divided into 5 block . In the above example, at most 3 Time , Divided into 4 block .

8. Split the string according to the specified length

If you want to split the string according to the specified length , You can use the following loops :

n = 3 # chunk length
chunks = [str[i:i+n] for i in range(0, len(str), n)]

In the next example , Given a character string consisting of three letter words, one connected by one , Let's put each letter word with 3 Cut out for length :

# Example to Split String to specific length Chunks
str = 'CarBadBoxNumKeyValRayCppSan'
n = 3
chunks = [str[i : i + n] for i in range(0, len(str), n)]
print(chunks)

Execution and output :
 Split the string according to the specified length .png
This example is applied to scenes with limited length after segmentation .

9. Replace multiple spaces with a single space

To replace multiple spaces in a string with a single space ,

  • Use split() Split the string with the default delimiter
  • Use join() Use a single space to connect the separated strings :
    " ".join(mystring.split())

mystring Contains consecutive spaces . Examples are as follows :

# Example to replace continuous multiple white spaces with single space
mystring = 'welome to python examples '
correctedstring = ' '.join(mystring.split())
print(correctedstring)

Execution and output :
 Replace multiple spaces with a single space .png
You can see , Even at the beginning and end of the string, there are multiple spaces , It's also filtered out .

10. Check if the string contains only letters

To check whether the string contains only letters, you can use isalpha() function , If it contains only letters, it will return True, Otherwise return to False.

bool = str1.isalpha()

Let's create a string and then see if it contains only letters :

# Example to check if String contains only Alpha
str1 = "Hello world. Welcome to Python Examples"
bool = str1.isalpha()
print('str1 contains only alphabets:', bool)

Execution and output :
 Check if the string contains only letters .png
str1 Besides the letters , It also contains two periods and a number of spaces , therefore isalpha() return False. Now let's use full letter strings for checking .

str1 = "HelloworldWelcometoPythonExamples"
bool = str1.isalpha()
print('str1 contains only alphabets:', bool)

Execution and output :
 Check if the string contains only letters 2.png

Reference material

版权声明
本文为[Defonds]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database