0

I'm really new to Python and programming in general, so I've been stuck for a while trying to figure out through searching the internet how to print a string to a length determined by a variable. This is one of the things I tried, for an example of what I'm attempting to do:

var1 = 6
string1 = "a random string"
print(string1[0,var1])

So I've been wondering if it is possible to use the stored value of a variable as a string indice or if there is another workaround that I haven't thought of or found on the rest of the internet.

Thanks for reading! :)

1
  • It should be print(string1[0 : var1]) You should use : instead of , Commented Sep 10, 2015 at 0:10

2 Answers 2

1

Yes, that works. Some background about slices is available in the Python documentation for Extended Slices. But instead of the comma use :

var1 = 6
string1 = "a random string"
print(string1[0:var1])
# Output: a rand
Sign up to request clarification or add additional context in comments.

Comments

1

Your problem is not using a variable as indice, but using tuple as indices, which you cannot do. If you wanna print the substring here's the code:

var1 = 6
string1 = "a random string"
print(string1[0:var1])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.