How to extract a substring from a string in Python?
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.
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.
| # | ID | Query | URL | Count |
|---|---|---|---|---|
| 0 | 12662 | en | https://en.ans.wiki/6139/how-to-extract-a-substring-from-a-string-in-python | 3 |