Question #6979   Submitted by Answiki on 10/22/2022 at 06:12:36 PM UTC

How to create a substring with the first N characters of another string in Python?

Answer   Submitted by Answiki on 10/22/2022 at 06:14:52 PM UTC

In Python, the string[:N] syntax extract the N first characters from a string:

substring = string[:N]

Here are some example:

string = "AnsWiki"

# Display: Ans
print ( string[:3] )

# Display: AnsWi
print ( string[:5] )

# Display: AnsWiki
print ( string[:7] )

# Display: AnsWi
print ( string[:-2] )

Try this example online on repl.it.

2 events in history
Answer by Answiki on 10/22/2022 at 06:14:52 PM

In Python, the string[:N] syntax extract the N first characters from a string:

substring = string[:N]

Here are some example:

string = "AnsWiki"

# Display: Ans
print ( string[:3] )

# Display: AnsWi
print ( string[:5] )

# Display: AnsWiki
print ( string[:7] )

# Display: AnsWi
print ( string[:-2] )

Try this example online on repl.it.

Question by Answiki 10/22/2022 at 06:12:36 PM
How to create a substring with the first N characters of another string in Python?
# ID Query URL Count

Icons proudly provided by Friconix.