Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Basic operation of python string

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "the basic operation of python string". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1 dealing with strings

Original string: add r before the quotation marks at the beginning of the string to make it the original string. "original string" completely ignores all escape characters and prints out all backslashes in the string.

A multiline string with triple quotes: a multiline string begins with 3 single quotes or 3 double quotation marks. All quotation marks, tabs, or line breaks between "triple quotes" are considered part of the string.

Multiline strings are often used as multiline comments.

String subscripts and slices: strings use subscripts and slices like lists.

String in and not in operators: like lists, in and not in operators can also be used for strings.

2 string methods upper (), lower (), isupper (), and islower ()

The upper () and lower () string methods return a new string where all letters of the original string are converted to uppercase or lowercase accordingly. The non-alphabetic characters in the string remain unchanged.

> spam='hello world' > spam.upper () 'HELLO WORLD' > spam'hello world' > spam= spam.upper () > > spam'HELLO WORLD'# uses islower () and isupper () to determine whether all letters in the string are lowercase and uppercase. > spam.islower () False > spam.isupper () True# this kind of call is also feasible > 'hello'.upper ()' HELLO' > 'HELLO'.lower ()' hello'

These methods do not change the string itself, but return a new string

3 isX string method

Isalpha () returns True if the string contains letters and is not empty

Isalnum () returns True if the string contains only letters and numbers and is not empty

Isdecimal () returns True if the string contains only numeric characters and is not empty

Isspace () returns True if the string contains only spaces, tabs, and newlines, and is not empty

Istitle () returns True if the string contains only words that begin with uppercase letters followed by lowercase letters.

The program repeatedly asks the user for age and password until they enter a valid value:

While True: print ('Enter your age:') age = input () if age.isdecimal (): break print (' please enter a number for you age') while True: print ('select a new password (letters and numbers only):') password = input () if password.isalnum (): break print ('passwords can only have letters and numbers.')

4 string methods startswith () and endswith ()

The startswith () and endswith () methods return True if the string they call starts or ends with the string passed in by the method, and False if not. If you want to check whether the beginning or end of a string is equal to another string instead of the entire string, these methods can be used instead of the equal operator = =.

5 string methods join () and split ()

The join () method is called on a string, and the argument is a list of strings that returns a string. The returned string is concatenated by each string in the passed-in list.

>', '.join ([' cat','rat','bat']) 'cat,rat,bat' >' '.join ([' my','name','is','Simon']) 'mynameisSimon' >' .join (['my','name','is','Simon'])' mynameisSimon' > 'ABC'.join ([' my','name','is','Simon']) 'myABCnameABCisABCSimon' >

The split () method does the opposite. It calls on a string and returns a list of strings.

>'my name is Simon'.split () ['my',' name', 'is',' Simon'] > 'myABCnameABCisABCSimon'.split ("ABC") [' my', 'name',' is', 'Simon']

By default, the string'my name is Simon' is separated by white space characters, such as spaces, tabs, or newline characters.

6 align text with rjust (), ljust (), and center () methods

The rjust () and ljust () string methods return the populated version of the string that called them, aligning the text by inserting spaces. These two methods

The first parameter is the integer length, which is used to align the string

The second optional parameter is to specify a fill character in place of the space character.

The center () string method is similar to ljust () and rjust (), but centers the text.

> 'hello'.rjust (10)' hello' > 'hello'.ljust (20)' hello' > 'hello'.rjust' * hello' > 'hello'.ljust' hello*' > 'hello'.center' = hello===''

Hello'.rjust (10) is to align to the right, put 'hello' in a string of 10 in length.' hello' has five characters and he will add five spaces to the left to get a string of 10 characters.

This is a small code that prints tabular data and flows out spaces:

Def printPicnic (itemsDict, leftWidth, rightWidth): print ('PICNIC ITEMS'.center (leftWidth + rightWidth,' -')) for k, v in itemsDict.items (): print (k.ljust (leftWidth,'.) + str (v) .rjust (rightWidth) picnicItems = {'sandwiches': 4,' apples': 12, 'cups': 4,' cookies': 8000} printPicnic (picnicItems, 12, 5) printPicnic (picnicItems, 20, 6)

The running results are as follows:

-PICNIC ITEMS--sandwiches.. 4apples. 12cups. 4cookies. 8000-PICNIC ITEMS-sandwiches. 4apples. 12cups. 4cookies. 8000

7 remove white space characters with strip (), rstrip (), and lstrip ()

The strip () string returns a new string with no white space characters at the beginning and end.

Lstrip () removes the white space character on the left

Rstrip () removes the white space character on the right

There is an optional string parameter that specifies that those characters on both sides should be deleted.

> spam = 'spamspamspambaconspameggsspamspam' > spam.strip (' spam') 'baconspamegg'

Passing the parameter 'spam', to the strip () method tells it to delete the occurrence of s, p, a, m at both ends of the string stored in the variable. The character order in the string passed into the strip () method does not matter. Strip ('spam') and strip (' mpsa') do the same thing.

8 pyperclip () module copy and paste string

The pyperclip module has copy () and paste () functions, which can send text like or receive text from a computer's clipboard. Send the output of the program to the clipboard, making it easy for him to paste into mail, word processors or other software.

Practice projects add unordered lists to wiki tags

Import pypercliptext = pyperclip.paste () lines = text.split ('\ n') for i in range (len (lines)): lines [I] ='*'+ Lines [I] text='\ n'.join (lines) pyperclip.copy (text) "basic manipulation of python string". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report