SoFunction
Updated on 2024-11-21

A short summary of string basics and applications in Python

In Python, strings can be enclosed in single or double quotes.' hello' is the same as "hello". You can use the print() function to display string text:

Example:

print("Hello")
print('Hello')

Assigning a string to a variable is accomplished by following the variable name with an equal sign and a string:

typical example

a = "Hello"
print(a)

multiline string

You can use three quotes to assign a multi-line string to a variable: for example, you can use three double quotes:

a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Or use three single quotes: example

a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Note: In the result, the line breaks are in the same place as in the code.

Strings are arrays

Like many other popular programming languages, strings in Python are byte arrays representing Unicode characters. However, Python does not have a character datatype; individual characters are simply strings with length 1. Elements of a string can be accessed using square brackets.

Example, to get the character at position 1 (remember, the first character is at position 0):

a = "Hello, World!"
print(a[1])

Iterate over the string

Since strings are arrays, we can use a for loop to iterate through the characters in a string.

For example, iterate over the letters in the word "banana":

for x in "banana":
  print(x)

Learn more about for loops in our Python For Loops chapter.

String length

To get the length of a string, use the len() function.

Example, len() function returns the length of the string:

a = "Hello, World!"
print(len(a))

Check String

To check for the presence of a particular phrase or character in a string, we can use the keyword in.

For example, check for the presence of "free" in the following text:

txt = "The best things in life are free!"
print("free" in txt)

Use it in an if statement:

Example, print only if "free" is present:

txt = "The best things in life are free!"
if "free" in txt:
  print("Yes, 'free' is present.")

Learn more about if statements in our Python If.... .Else chapter to learn more about if statements.

Check if it does not exist

To check if a certain phrase or character does not exist in a string, we can use the keyword not in.

For example, check that "expansive" does not exist in the following text:

txt = "The best things in life are free!"
print("expensive" not in txt)

Use it in an if statement:

Example, print only if "expansive" does not exist:

txt = "The best things in life are free!"
if "expensive" not in txt:
  print("No, 'expensive' is NOT present.")

thin section of specimen for examination (as part of biopsy)

You can use the slice syntax to return a series of characters. , specify the start index and end index, separated by colons, to return part of a string.

Example:, get the characters from position 2 to position 5 (excluding position 5):

b = "Hello, World!"
print(b[2:5])

Note: The first character is indexed at 0. Slicing from the beginning, if the starting index is omitted, the range will start from the first character:

Example, get the characters from the beginning to position 5 (excluding position 5):

b = "Hello, World!"
print(b[:5])

Slicing to the end

If the end index is omitted, the range will go all the way to the end:

Example to get the characters from position 2 to the end:

b = "Hello, World!"
print(b[2:])

negative indexing

Slices from the end of the string using a negative index:

Example, get characters: from: "o" in "World!" (position -5) to, but not including: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])

Python has a set of built-in methods that can be used with strings.

banker's anti-fraud numerals

Example: The upper() method converts a string to uppercase:

a = "Hello, World!"
print(())

lowercase (letters)

Example: The lower() method converts a string to lowercase:

a = "Hello, World!"
print(())

Remove blanks

Whitespace is the space before and/or after the actual text, usually you want to remove this space.

Example, the strip() method removes any spaces from the beginning or the end:

a = " Hello, World! "
print(()) # come (or go) back "Hello, World!"

Replacement String

Example, the replace() method replaces a string with another string:

a = "Hello, World!"
print(("H", "J"))

split string

The split() method returns a list, where the text between the specified separators becomes list items.

Example, the split() method splits the string into substrings if it finds an instance of the separator:

a = "Hello, World!"
print((",")) # come (or go) back ['Hello', ' World!']

string concatenation

To concatenate or combine two strings, you can use the + operator.

Example:, combine variable a with variable b into variable c:

a = "Hello"
b = "World"
c = a + b
print(c)

example, to add a space between them, add a " ":

a = "Hello"
b = "World"
c = a + " " + b
print(c)

String Formatting

As we learned in the Python Variables chapter, we can't combine strings and numbers like this:

Example:

age = 36
txt = "My name is John, I am " + age
print(txt)

However, we can combine strings and numbers using the format() method!

The format() method takes the passed arguments, formats them, and places them in the string at the placeholder {}:

Example, using the format() method to insert a number into a string:

age = 36
txt = "My name is John, and I am {}"
print((age))

The format() method accepts an unlimited number of arguments and puts them into the appropriate placeholders:

typical example

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print((quantity, itemno, price))

You can use the index number {0} to ensure that the argument is placed in the correct placeholder:

typical example

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print((quantity, itemno, price))

escape character

To insert characters that are not allowed in the string, use escape characters.

The escape character is a backslash\ followed by the character to be inserted.

An example of an illegal character is the insertion of double quotes into a string enclosed by double quotes:

Example: If you use double quotes in a string enclosed by double quotes, an error will occur:

txt = "We are the so-called "Vikings" from the north."

To solve this problem, use the escape character \:

Example escape characters allow you to use double quotes in situations where they would not normally be allowed:

txt = "We are the so-called \"Vikings\" from the north."

Other escape characters used in Python:

\'  single quote  
\\  backslash (computing)  
\n  line break  
\r  carriage return  
\t  tabular character  
\b  backspace (computing)  
\f  page break  
\ooo  octal value  
\xhh  hexadecimal value

Python String Methods

Python has a set of built-in methods that can be used with strings.

Note: All string methods return new values. They do not change the original string.

capitalize() Convert the first character to uppercase
casefold() Convert strings to lowercase
center() Returns a centered string
count() Returns the number of occurrences of the specified value in the string
encode() Returns the encoded version of the string
endswith() If the string ends with the specified value,then it returnsTrue
expandtabs() Setting the tab size of a string
find() Searches for a specified value in a string and returns the location where it was found.
format() Formatting a specified value in a string
format_map() Formatting a specified value in a string
index() Searches for a specified value in a string and returns the location where it was found.
isalnum() If all characters in the string are alphanumeric characters,then it returnsTrue
isalpha() If all the characters in the string are in the alphabet,then it returnsTrue
isascii() If all the characters in the string areASCIIcharacter,then it returnsTrue
isdecimal() If all the characters in the string are十进制character,then it returnsTrue
isdigit() If all the characters in the string are数字,then it returnsTrue
isidentifier() 如果character串是标识符,then it returnsTrue
islower() If all the characters in the string are小写,then it returnsTrue
isnumeric() If all the characters in the string are数字,then it returnsTrue
isprintable() If all the characters in the string are可打印character,then it returnsTrue
isspace() If all the characters in the string are空白character,then it returnsTrue
istitle() 如果character串遵循标题规则,then it returnsTrue
isupper() If all the characters in the string are大写,then it returnsTrue
join() 将可迭代对象的元素连接到character串的末尾
ljust() 返回character串的左对齐版本
lower() Convert strings to lowercase
lstrip() 返回character串的左修剪版本
maketrans() Returns the conversion table used for conversion
partition() Returns a tuple,其中character串分为三个部分
replace() 返回一个character串,where the specified value is replaced with the specified value
rfind() 搜索character串中的指定值并返回其找到的最后位置
rindex() 搜索character串中的指定值并返回其找到的最后位置
rjust() 返回character串的右对齐版本
rpartition() Returns a tuple,其中character串分为三个部分
rsplit() 在指定的分隔符处拆分character串,and returns a list of
rstrip() 返回character串的右修剪版本
split() 在指定的分隔符处拆分character串,and returns a list of
splitlines() 在换行符处拆分character串,and returns a list of
startswith() 如果character串以指定值开头,then it returnsTrue
strip() 返回character串的修剪版本
swapcase() case sensitive,Lowercase to uppercase,vice versa
title() 将每个单词的第一个character转换为大写
translate() 返回一个翻译后的character串
upper() 将character串转换为大写
zfill() Fill the beginning with the specified number of0值的character串

ultimate

To this point this article on Python string basis and application of the article is introduced to this, more related to Python string basis and application of the content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!