Question #6139   Submitted by Answiki on 05/13/2022 at 06:01:31 PM UTC

How to extract a substring from a string in Python?

Answer   Submitted by Answiki on 05/13/2022 at 06:03:31 PM UTC

In Python, the syntax string[i:j] is used to extract characters or substring between indexes i (include) and j (exclude). Note that the first character of the string is at index 0.

substring = string[i:j]

Here are some examples:

string = "AnsWiki"

# Affiche : Wi
print ( string[3:5] )

# Displays: Wiki
print ( string[3:7] )

# Displays: AnsWiki
print ( string[0:7] )

# Displays: Ans
print ( string[0:-4] )

# Displays: Wi
print ( string[-4:-2] )

Test this example online on repl.it.

2 events in history
Answer by Answiki on 05/13/2022 at 06:03:31 PM

In Python, the syntax string[i:j] is used to extract characters or substring between indexes i (include) and j (exclude). Note that the first character of the string is at index 0.

substring = string[i:j]

Here are some examples:

string = "AnsWiki"

# Affiche : Wi
print ( string[3:5] )

# Displays: Wiki
print ( string[3:7] )

# Displays: AnsWiki
print ( string[0:7] )

# Displays: Ans
print ( string[0:-4] )

# Displays: Wi
print ( string[-4:-2] )

Test this example online on repl.it.

Question by Answiki 05/13/2022 at 06:01:31 PM
How to extract a substring from a string in Python?
# ID Query URL Count

Icons proudly provided by Friconix.