Skip to content

Data collection - str()


Properties of list:

  • the data cannot be modifed after defined
  • means that changes will not apply on old variable name, but you can create a new variable name to store it.

  • Related to basic usage of string: Click here.
  • str() can be considered as data container because the text inside a str() can be standalone.

Example:

py
text = str("Hi")
print(text[0]) 
print(text[1])

Output:

H
i

Usage & Method

str-collection-usage.py

1. Get element in a string

py
str_text = str("Hi, John's Dog")
#               01234567891111
#                         0123

# get element in a string
print(str_text[11]) # D
print(str_text[12]) # o
print(str_text[13]) # 9

Output:

D
o
g

2. Get the length of a string, len()

py
# get length of the string
print(len(str_text)) # 14

Output:

14

3. Find a number of repeated text, text.count(match_value)

py
# find number of o in a str
print(str_text.count("o"))

Output:

2

4. Method - index()

py
# index of text "o"
print(str_text.index("o"))

Output:

5

Info

It only will return first match position / index.

5. Method - replace()

py
# Replace dog -> cat
new_str_text = str_text.replace("Dog", "Cat")
print(new_str_text)

Info

It can't change the old string directly, it only can store the changes on a new variable.

Output:

Hi, John's Cat

6. Method - split() 切分

py
# split()
new_text = str("Hello Hello John")
results = new_text.split() # remove space ( )
print(results)
print(type(results))

Output:

['Hello', 'Hello', 'John']
<class 'list'>

Info

  • It can't change the old string directly, it only can store the changes on a new variable.
  • And It will returning a new list.

7. Method - strip() 规整操作

  • Will remove the text contains if it matches (on front and back only)
  • if matches value = "12", it will remove if contains ["1", "2"]
py
new_text_2 = "######21####Hello Ben#############12##"
stripped_text_2 = new_text_2.strip("12#")
print(stripped_text_2)

Output:

Hello Ben

Conclusion

String data container method and usage conclusion

String data container properties conclusion

Comprehensive Example

Given:

Hi Hello Hola

  • Find number of time that 'H' exist.

  • replace the space " " to "|".

  • Spliting the string based on the "|"

  • Hints: count, replace, split


str-data-collection-ex.py

py
text = str("Hi Hello Hola")

# Find number of time that 'H' exist.
print(text.count("H"))

# replace the space " " to "|".
new_text = text.replace(" ", "|")
print(new_text)

# Spliting the string based on the "|"
new_text_2 = new_text.split("|")
print(new_text_2)

Output:

3
Hi|Hello|Hola
['Hi', 'Hello', 'Hola']