Understanding Python Strings

01Strings (str)

Strings (str), as the name implies, are understood as follows. Characters, letters, words, numbers; symbols, various signs; when enclosed in single quotes ‘ ‘ or double quotes ” “, they form a string.

a = 'Hello World'print(type(a)) #<class 'str'>    'Hello World' is of string type

Strings (str) are a sequence of characters enclosed in single or double quotes. For example:

'爱睡觉的红小豆儿''123'"你好世界!""Hello&World"# All of these are strings

02Creating Strings

  • Using single or double quotes (in English/horizontal mode)

a = 'Hello World'  ✅b = "你好"   ✅# Double or single quotes cannot be in Chinese/full-width mode    “你好” ❌“Hello” ❌
  • Use consistent quotes at both ends; mixing single and double quotes is not allowed

'fa"  ❌"jfkjkdfd'  ❌# Mixing single and double quotes is not allowed

Strings can be output using the print() function

a = 'Hello'b = 'World'print(a)   # Prints Hello
print(b)   # Prints World

03Simple String Operations

  • String Concatenation

The plus sign + can concatenate strings

a = '你好'b = '同学'print(a + b)  # 你好同学  Two strings concatenated via addition
  • Multiplying Strings with Numbers

String a multiplied by number n can concatenate n copies of string a

a = '你好'print(a * 3) # Prints 3 '你好'   你好你好你好  print(a * 5) # Prints 5 '你好'   你好你好你好你好你好b = '-'print(b * 10) # Prints 10 '-'    ----------

04Type Function

type() function: Check type

Using the type() function helps us check what type the current variable or data belongs to.

Fill in the variable or data you want to check within the parentheses of type().

x = 'Hello'y = "张三"a = 200b = 54.99c = Trueprint(type(x)) # <class 'str'>  String typeprint(type(y)) # <class 'str'>  String typeprint(type(a)) # <class 'int'>  Integer typeprint(type(b)) # <class 'float'> Float typeprint(type(c)) # <class 'bool'> Boolean type

05String Operations

A string is an ordered sequence of multiple characters. For example s = ‘abcdefg’

Similar to lists, string indexing starts from “0”, and it also supports reverse indexing from “-1”. Using a single index value can retrieve a specified character, or multiple index values can be used for slicing to obtain multiple characters. To sequentially retrieve each character in the string, a loop can be implemented.

String Indexing, Slicing, and Traversing

Assuming there is a string

 s = 'abcdefg'

Indexing: Retrieve a specified character. For example

 s = 'abcdefg's[0]   # Result is 'a's[-1]   # Result is 'g'

Slicing: Retrieve a continuous sequence of characters. For example

s[1:4] #'bcd's[:4]  #'abcd's[1:]  #'bcdefg's[:]   #'abcdefg'

Traversing: Sequentially retrieve each character in the string. A loop can be implemented. For example:

s = 'codepku'for c in s:    print(c)

The output will be:

codepku

String Formatting

Currently, there are three common methods for string formatting: %, format(), and f-strings, where f-strings are similar to format() but only support Python 3.6 and above.

The following program compares the three methods to print the string “大家好,我是学学,今年5岁啦!”, where the name “学学” and age “5” are stored in the variables name and age respectively.

name = '学学'age = 5# Using string concatenation for formattingprint('大家好,我是' + name + ',今年' + str(age) + '岁啦!')# Using % for formattingprint('大家好,我是%s,今年%d岁啦!' % (name, age))# Using format() for formattingprint('大家好,我是{},今年{}岁啦!'.format(name, age))print('大家好,我是{0},今年{1}岁啦!'.format(name, age))print('大家好,我是{0},今年{1}岁啦!大名也是{0}'.format(name,age))# Using f-strings for formattingprint(f'大家好,我是{name},今年{age}岁啦!')

It can be seen that f-strings retain the clarity and flexibility of template strings, while further increasing the readability of the program by embedding variables within placeholders.

%f: Outputs data according to the actual length of floating-point data.

print('第一名考了%f' % 288)  # 第一名考了288.000000
%f Defaults to 6 decimal places
%af Where a controls the total number of digits, defaults to 6 decimal places, with 1 digit for the decimal point, and the left side is filled with spaces if not enough
%.bf Indicates b decimal places after the decimal point
%a.bf Indicates a total of a digits and b decimal places

If the displayed number of floating-point digits exceeds the set total number of digits, it will display according to the actual number of digits.

%s: Outputs data according to the actual length of the string

print('我的名字叫%s' % '张三')  #我的名字叫张三

Extension

Both format() and f-strings can enrich format control in the template string placeholders using the guide symbol “:”, for example:

print('{:=^21}'.format('codepku'))

The output will be:

=======codepku=======

Where “21” sets the width after formatting, “^” sets the alignment【”<“, “^”, “>” indicate left, center, and right alignment respectively】, and “=” sets the fill character.

Common String Handling Methods

In addition to the format() method for string formatting, Python also provides a series of methods for handling strings, such as:

Common String Handling Methods
Method str.startswith(prefix)
Function

Determines whether the string str starts with prefix;

Use endswith() for ending checks

Method str.count(sub)
Function Counts the occurrences of substring sub in str
Method str.upper()
Function

Converts all characters in string str to uppercase;

Use lower() for lowercase conversion

Method str.strip(chars)
Function Removes characters specified by chars from both ends of string str
Method str.replace(old,new)
Function Replaces substring old in string str with new
s = 'abcdabcdabababa'# Check if string str starts with prefixs.startswith('ab') # Trues.startswith('b') # False# Check if string str ends with prefixs.endswith('ba') # Trues.endswith('fxxd') # False
s = 'abcdabcdabababa'# Count occurrences of substring sub in strs.count('ab') # 5s.count('cd') # 2s.count('x') # 0
s = 'Hello World'# Convert all characters in string str to uppercase;print(s.upper()) # HELLO WORLD# Convert all characters in string str to lowercase;print(s.lower()) # hello world
# Remove specified characters from both ends of string str2str2= "*****this is **string** example....wow!!!*****"print (str2.strip( '*' ))  # Specified string *# this is **string** example....wow!!!str1 = '   hello world  'print(str1.strip()) # hello world
str1 = '0hello world1'print(str1.strip('0'))# hello world1
# Replace substring old with new in string str# str.replace(old,new)str1 = 'hello world'str2 = str1.replace('hello','你好')print(str2)# 你好 world

06Practice

1. Which of the following options is a correct string ()

A、’abc” ab”

B、’abc’ ab’

C、”abc”ab”

D、”abc\”ab”

2. Given s=’Hello Kai TuoZhe’, executing print(s [4:11]) outputs ()

A、lo Kai Tu

B、lo Kai T

C、o Kai Tu

D、o Kai T

3. Please ask

print("我是%s,身高%.2米" %("小明",1.4))

What is the output ()

A、我是小明,身高1.4米

B、我是小明,身高1.40000米

C、我是小明,身高1.40米

D、我是%s,身高%.2米” %(“小明”,1.4)

3. (Note: The input() function does not allow any information to be added in parentheses)

Programming Implementation

Input a string containing the character ‘a’ (length less than 1000), output the number of occurrences of character ‘a’ in the string.

Input Description

Input a string containing the character ‘a’

Output Description

Output an integer indicating the number of occurrences of character ‘a’ in the string

Sample Input

ab!a

Sample Output

2

Leave a Comment